【问题标题】:How do I update a variable inside a Runnable?如何更新 Runnable 中的变量?
【发布时间】: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


    【解决方案1】:
    Thread thread = new Thread(myRunnable);
    thread.run();
    myRunnable.setActive(false);
    

    第三行只会在 run() 方法返回后执行。您在单个线程中按顺序执行所有内容。第二行应该是

    thread.start();
    

    并且该字段应该是可变的。

    但是请注意,将 active 字段设置为 false 将使线程进入一个忙碌的循环,什么都不做,而是通过不断循环消耗 CPU。你应该使用锁来等待,直到你可以恢复。

    【讨论】:

    • 非常感谢。解决了。我将如何实现锁定功能等待?
    • 例如使用Condition
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-16
    • 2012-04-24
    • 2020-07-11
    • 2019-02-10
    • 1970-01-01
    • 1970-01-01
    • 2019-06-01
    相关资源
    最近更新 更多