有序性问题:
static int a, b, c, d;
public static void main(String[] args) throws InterruptedException {
int z = 0;
while (true) {
a=0;
b=0;
c=0;
d=0;
Thread t1 = new Thread(() -> {
a = 10;
b = d;
});
t1.start();
Thread.sleep(1000);
Thread t2 = new Thread(() -> {
c = 20;
d = a;
});
t2.start();
t1.join();
t2.join();
z++;
if (b == 0 && d == 0) {
System.out.println("ok----"+z);
break;
}
}
}
2.可见性问题:
private static boolean flag = false;
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(()->{
System.out.println("开始");
while (!flag){
synchronized ("1"){
}
}
System.out.println("应该变的"+flag);
});
t1.start();
Thread.sleep(1000);
Thread t2 = new Thread(()->{
flag=true;
System.out.println("t2线程"+flag);
});
t2.start();
}
使用定义synchronized ("1"){}锁进行解决