LqS*_*qS2 6 java multithreading
好吧,我遇到了一个惊人的问题......
public class Test {
private boolean[] state = new boolean[]{false, false};
public void createThread() {
Thread th1 = new Thread(() -> {
try {
System.out.println("1");
Thread.sleep(2000);
state[0]=true;
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread th2 = new Thread(() -> {
try {
System.out.println("2");
Thread.sleep(2000);
state[1] = true;
} catch (InterruptedException e) {
e.printStackTrace();
}
});
th1.start();
th2.start();
}
public static void main(String args[]) throws InterruptedException {
Test test = new Test();
test.createThread();
while (true) {
// Thread.sleep(1);
if (test.state[0] && test.state[1]) {
System.out.println("stopped");
break;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果我不添加Thread.sleep(1)语句或其他代码,则"停止"不会被打印.如果我添加内容while,将打印"停止".这会怎么样?每个答案都有帮助.
答案可能很简单,但在于细节.
你的阵列,它保持状态没有被标记为volatile,因此if-statement在你的while循环不会被迫使用最新值.
简单地改变
private boolean[] state = new boolean[] { false, false };
至
private volatile boolean[] state = new boolean[] { false, false };
会诀窍.
| 归档时间: |
|
| 查看次数: |
99 次 |
| 最近记录: |