为什么这个简单的线程程序卡住? [英] Why does this simple threaded program get stuck?
本文介绍了为什么这个简单的线程程序卡住?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
看看这个简单的Java程序:
Take a look at this simple Java program:
import java.lang.*;
class A {
static boolean done;
public static void main(String args[]) {
done = false;
new Thread() {
public void run() {
try {
Thread.sleep(1000); // dummy work load
} catch (Exception e) {
done = true;
}
done = true;
}
}.start();
while (!done);
System.out.println("bye");
}
}
在一台机器上打印bye在另一台机器上,它不打印任何东西,永远坐在那里。为什么?
On one machine, it prints "bye" and exits right away, while on another machine, it doesn't print anything and sits there forever. Why?
推荐答案
这是因为 boolean
不是 volatile
,因此线程
允许缓存它的副本,从不更新它们。我会推荐一个 AtomicBoolean
- 这将防止您可能有的任何问题。
This is because your boolean
is not volatile
, therefore Thread
s are allowed to cache copies of it and never update them. I would recommend an AtomicBoolean
- that will prevent any issues you may have.
public static void main(String args[]) {
final AtomicBoolean done = new AtomicBoolean(false);
new Thread() {
public void run() {
done.set(true);
}
}.start();
while (!done.get());
System.out.println("bye");
}
这篇关于为什么这个简单的线程程序卡住?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文