如何创建一个等待布尔变量变为true的线程?
我有一个函数需要在布尔变量为真时调用。 我尝试在线程中使用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("first\n"); // 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("first\n"); 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("first\n"); r.latch.countDown(); } }
要真正注意到差异,请在println("first")
Thread.sleep(20000)
之后添加一个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("first\n"); 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("first\n"); // set conndition to true condition.notify(); } }
如果你想要更高级的通知方案,你也可以查看java.util.concurrent
,了解让线程在更有趣的条件下等待的更强大的方法。 所有这些都比在旋转条件成真之前更加节省CPU,并且由于Java内存模型的细微之处,它们不太可能引入并发错误。
- 如何在不进行模运算的情况下将Java BigInteger提升为BigInteger的强大function?
- Integer.parseInt(string)实际上是如何工作的?
- 在Apache Tomcat中运行的Web应用程序中查找内存泄漏的建议
- k-shortest(替代)路径算法,java实现
- 使用Jackson(Joda-Time模块)进行DateTime反序列化的默认时区
- 从web.xml的安全约束中排除JSP
- 当每个人都对OSGi进行标准化时,为什么Sun会发明另一个模块系统?
- 使用Apache Tika在solr中的PDF文件的ContentExtraction
- Javaexception – 在没有try catch的情况下处理exception