[英]How do I update a variable inside a Runnable?
I'm trying to create a Runnable that keeps running, but I need to makes changes to a variable from outside, to pause or resume the work that the Runnable is doing. 我试图创建一个可运行的Runnable,但是我需要从外部对变量进行更改,以暂停或恢复Runnable正在进行的工作。
This is my Runnable implementation: 这是我的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;
}
In my main class I call: 在我的主班上,我打电话给:
Thread thread = new Thread(myRunnable);
thread.run();
myRunnable.setActive(false); //This does not work!!!
//The boolean remains true inside myRunnable.
I've tried with the "volatile" modifier on active, but still it won't update. 我已经尝试在活动状态下使用“ volatile”修饰符,但仍不会更新。 Any ideas are greatly appreciated.
任何想法都将不胜感激。
Thread thread = new Thread(myRunnable);
thread.run();
myRunnable.setActive(false);
The third line will only execute after the run() method has returned. 第三行仅在run()方法返回后执行。 You are executing everything in a single thread, sequentially.
您正在按顺序在单个线程中执行所有操作。 The second line should be
第二行应该是
thread.start();
And the field should be volatile. 而且该领域应该是易变的。
Note, however, that setting the active field to false will make the thread enter a busy loop doing nothing, but consuming CPU by looping constantly. 但是请注意,将active字段设置为false将使线程进入忙碌循环,什么也不做,而是通过不断循环来消耗CPU。 You should rather use a lock to wait until you can resume.
您宁可使用锁来等待,直到可以恢复。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.