如何实现一个持续活动的循环以检查更改(布尔值)?

时间:2019-06-02 22:02:09

标签: java

我创建了一个布尔b。我想不断检查b是否改变。如果是这样,则应执行操作e

1 个答案:

答案 0 :(得分:2)

使用外部线程:

volatile boolean b = true;
new Thread(() -> {
  while (true) {
    boolean lastB = b;
    while (b == lastB) {
      //If you want a delay between each check:
      try {
        Thread.sleep(/*delay in ms*/);
      } catch (InterruptedException ignored) {} 
    }
    //Do something if b changes
  }
}).start();