[英]Make me understand this thread sync failure
I'll cut it short. 我会简短地说。
Given this code: 给出以下代码:
public class Test {
private static long counter = 1000000;
public static void main(String[] args) {
T t = new T();
t.start();
while(counter >= 0){
counter--;
System.out.println(counter);
}
System.out.println(t.isAlive());
}
private static class T extends Thread{
@Override
public void run() {
while(counter > 0);
System.out.println("end reached");
}
}
}
Why in the name of the gods doesn't T print "end Reached"? 为什么不以众神的名义印刷“伸手可及的距离”? Counter goes down to -1 and t is alive. 计数器下降到-1,t仍然有效。 If I decrease the counter it sometimes work. 如果我减少计数器,它有时会起作用。
you need to make counter volatile
. 您需要使计数器变得volatile
。 Thread T is using a local copy. 线程T正在使用本地副本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.