如何创建一个等待布尔变量变为true的线程?

Igo*_*gor 2 java multithreading

我有一个函数需要在布尔变量为真时调用.我尝试在线程中使用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;

    }

}
Run Code Online (Sandbox Code Playgroud)

结果应该是:

first
second
Run Code Online (Sandbox Code Playgroud)

Mar*_*nik 14

不要忙 - 等待这样的条件.使用阻塞习语.对于你的简单案例,你会逃避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;
  }
}
Run Code Online (Sandbox Code Playgroud)

为了比较,一个程序有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();
  }
}
Run Code Online (Sandbox Code Playgroud)

要真正注意到差异,请添加一个Thread.sleep(20000)后续内容println("first")听取计算机风扇声音的差异,努力消耗第一个程序浪费的能量.

  • 浪费CPU是一个非常严重的问题,不仅仅是在性能方面.它浪费了更有形的东西:**能量**.即使你不关心电费或环境,**每个人**都关心他们设备的电池寿命. (8认同)
  • @Igor - 它将不必要地使用CPU. (3认同)