如何创建一个等待布尔变量变为true的线程? [英] How to create a thread that waits for a boolean variable to become true?
问题描述
我有一个函数需要在布尔变量为真时调用。我尝试在线程中使用while循环,但它不起作用。这是我尝试过的:
I have a function that needs to be called once a boolean variable is true. I tried using a while loop in a thread but it doesn't work. Here is what I've tried:
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("first\n");
// set conndition to true
condition = true;
}
}
结果应该是是:
first
second
推荐答案
请勿忙碌等待以获取此类条件。使用阻塞习语。对于你的简单情况,你会得到一个新的CountDownLatch(1)
。首先,这是你的代码,但修复后编译并运行你期望的方式:
Do not busy-wait for such conditions. Use a blocking idiom. For your simple case you would get away with a new CountDownLatch(1)
. First, here's your code, but fixed to compile and run the way you expect:
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("first\n");
r.condition = true;
}
}
作为比较,一个<$ c $的程序c> 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("first\n");
r.latch.countDown();
}
}
要真正注意到差异,请添加 Thread.sleep(20000)
在 println(first)
之后,听到声音的差异您的计算机粉丝努力消耗第一个程序浪费的能量。
To truly notice the difference, add a Thread.sleep(20000)
after println("first")
and hear the difference in the sound of your computer's fan working hard to dissipate the energy the first program is wasting.
这篇关于如何创建一个等待布尔变量变为true的线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!