遇到一个并发取值问题
① 如下定义两个线程t1和t2,都能正常执行完成。
private static Test test = new Test();
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
while (true) {
if (test.object != null) {
break;
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("thread-1 done");
}, "thread-1");
t1.start();
Thread t2 = new Thread(new Runnable() {
@SneakyThrows
@Override
public void run() {
Thread.sleep(10);
test.object = new Object();
System.out.println("thread-2 done");
}
}, "thread02");
t2.start();
}
static class Test {
public Object object;
}
② 如果把t1的定义改成:
Thread t1 = new Thread(() -> {
while (true) {
if (test.object != null) {
break;
}
}
System.out.println("thread-1 done");
}, "thread-1");
那t1一直死循环无法执行完成,这是为什么?这里先不考虑用volatile