如何在java中给线程发信号?

oug3syen  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(220)

我有一个进程正在运行,它创建一个线程对象并运行它。现在根据进程中的一些事件,我希望线程做出相应的React。更准确地说,如果commonvar变为true,那么线程b应该在while循环中暂停。当commonvar变为false时,线程b应该从run()方法的开头开始。
请注意,线程b不会写入commonvar。它只是在读。

public class B implements runnable
{
    Boolean commanVar;

    public B(boolean commanVar) {
        this.commonVar = commonVar;
    }

    public void run()
    {
        while(true) {
        // do some processing
        }
    }
}

public class A
{
    public static void main(String[] args) {
        Boolean commonVar = false;
        Thread threadB = new Thread(new ClassB(commonVar));
        threadB.start();
        // some processing will happen and because of that commonVar will change.
    }
}
8dtrkrch

8dtrkrch1#

不要停止线程。相反,发出任务(通过blockingqueue)或信号(通过信号量),让它们在有输入时运行,在输入用尽时挂起。

相关问题