Java 如何更新Runnable中的变量?

Java 如何更新Runnable中的变量?,java,multithreading,runnable,Java,Multithreading,Runnable,我试图创建一个持续运行的Runnable,但我需要从外部对变量进行更改,以暂停或恢复Runnable正在执行的工作 这是我的可运行实现: private boolean active = true; public void run() { while (true) { if (active) { //Need to modify this bool from outside //Do Something } } }

我试图创建一个持续运行的Runnable,但我需要从外部对变量进行更改,以暂停或恢复Runnable正在执行的工作

这是我的可运行实现:

private boolean active = true;


 public void run() {
    while (true) {
        if (active) { //Need to modify this bool from outside
            //Do Something
        }
    }
}

 public void setActive(boolean newActive){
     this.active = newActive;
 }
在我的主课上,我叫:

Thread thread = new Thread(myRunnable);
thread.run();
myRunnable.setActive(false); //This does not work!!! 
                                 //The boolean remains true inside myRunnable.
我尝试过在活动状态下使用“volatile”修改器,但它仍然不会更新。非常感谢您的任何想法

Thread thread = new Thread(myRunnable);
thread.run();
myRunnable.setActive(false);
第三行仅在run()方法返回后执行。您正在单线程中按顺序执行所有操作。第二行应该是

thread.start();
这个领域应该是不稳定的


然而,请注意,将active字段设置为false将使线程进入一个繁忙的循环,而不做任何事情,而是通过不断循环来消耗CPU。您应该使用锁等待恢复。

非常感谢。解决了。如何实现锁定等待功能?例如,使用。