我有一个函数,一旦布尔变量为真,就需要调用它。我尝试在线程中使用 while 循环,但它不起作用。这是我尝试过的:
public class MyRunnable implements Runnable {
public void run() {
while (true) {
if (conditions == true) {
System.out.println("second");
break;
}
}
}
public static void main(String args[]) {
boolean condition = false;
(new Thread(new MyRunnable())).start();
System.out.println("firstn");
// set conndition to true
condition = true;
}
}
结果应该是:
first
second
不要忙着等待这种情况。使用阻止成语。对于您的简单情况,您将侥幸逃脱new CountDownLatch(1)
.首先,这是您的代码,但已修复以按预期方式编译和运行:
public class MyRunnable implements Runnable {
volatile boolean condition = false;
public void run() {
while (true) {
if (condition) {
System.out.println("second");
break;
}
}
}
public static void main(String args[]) {
final MyRunnable r = new MyRunnable();
new Thread(r).start();
System.out.println("firstn");
r.condition = true;
}
}
为了进行比较,具有CountDownLatch
的程序:
public class MyRunnable implements Runnable {
final CountDownLatch latch = new CountDownLatch(1);
public void run() {
try { latch.await(); } catch (InterruptedException e) {}
System.out.println("second");
}
public static void main(String args[]) {
final MyRunnable r = new MyRunnable();
new Thread(r).start();
System.out.println("firstn");
r.latch.countDown();
}
}
要真正注意到差异,请在println("first")
后添加一个Thread.sleep(20000)
,并听到计算机风扇努力消散第一个程序浪费的能量的声音的差异。
这似乎是java等待通知构造的地方。
public class MyRunnable implements Runnable {
public run() {
synchronized(this) {
try {
wait();
} catch (InterruptedException e) {
}
}
System.out.println("second");
}
public static void main(String args[]) {
Runnable r = new MyRunnable();
Thread t = new Thread(r);
t.start();
System.out.println("firstn");
synchronized (r) {
r.notify();
}
}
}
不要那样做。相反,您可以使用 Object
的内置notify()
和wait()
方法,如下所示:
public class MyRunnable implements Runnable {
private final Object condition;
public MyRunnable(Object condition) {
this.condition = condition;
}
public void run() {
condition.wait();
System.out.println("second");
}
public void go(String args[]) {
Object condition = new Object();
(new Thread(new MyRunnable(condition))).start();
System.out.println("firstn");
// set conndition to true
condition.notify();
}
}
如果你想要更高级的通知方案,你也可以在java.util.concurrent
寻找更强大的方法,让线程等待更有趣的条件。所有这些都将比仅仅旋转直到条件为真要高得多,并且由于Java内存模型中的微妙之处,它们不太可能引入并发错误。