第12-6这一节,我的idea在编辑代码的时候,CountDownLatch latch = new CountDownLatch(1); 这行代码,必须要加final关键字,才不报错。提示:Variable ‘latch’ is accessed from within inner class, needs to be declared final。
为什么,看视频,老师好像没有加这个,都能正常运行呢。
![图片描述](http://img1.sycdn.imooc.com/szimg/5e0603b50859b8ec12161312.jpg
完整代码:
package concurrencyknowledge.jmm;
import java.util.concurrent.CountDownLatch;
/**
* @Created by jasyu 2019/12/26
*
* 1. a=1;x=b(0);b=1;y=a(1) x=0,y=1
* 2. b=1;y=a(0);a=1;x=b(1) x=1,y=0
* 3. b=1;a=1;x=b(1);y=a(1) x=1,y=1
*/
public class OutOfOrderException {
private static int a = 0, x = 0;
private static int b = 0, y = 0;
public static void main(String[] args) throws InterruptedException {
int i = 0;
for (; ;) {
i++;
a = 0;
x = 0;
b = 0;
y = 0;
final CountDownLatch latch = new CountDownLatch(1);
Thread one = new Thread(new Runnable() {
public void run() {
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
a = 1;
x = b;
}
});
Thread two = new Thread(new Runnable() {
public void run() {
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
b = 1;
y = a;
}
});
one.start();
two.start();
latch.countDown();
one.join();
two.join();
String result = "[run " + i + "times] x = " + x + ", y = " + y;
if (x == 1 && y == 1) {
System.out.println(result);
break;
} else {
System.out.println(result);
}
}
}
}
登录后可查看更多问答,登录/注册