【发布时间】:2016-03-23 21:56:12
【问题描述】:
我正在尝试创建一个持续运行的 Runnable,但我需要从外部对变量进行更改,以暂停或恢复 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”修饰符,但它仍然不会更新。任何想法都非常感谢。
【问题讨论】:
标签: java multithreading runnable