如何在java中为线程发送信号?

如何在java中为线程发送信号?,java,multithreading,concurrency,Java,Multithreading,Concurrency,我有一个进程正在运行,它创建一个线程对象并运行它。现在,根据进程中的一些事件,我希望线程做出相应的反应。更准确地说,如果commonVar变为true,那么线程B应该在while循环中暂停。然后,当commonVar变为false时,线程B应该从run()方法的开头开始 请注意,线程B不会写入commonVar。它只是在读 public class B implements runnable { Boolean commanVar; public B(boolean comma

我有一个进程正在运行,它创建一个线程对象并运行它。现在,根据进程中的一些事件,我希望线程做出相应的反应。更准确地说,如果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.
    }
}

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

这是否回答了您的问题?获取所需内容的唯一方法是线程B定期检查标志的值,并在适当时暂停自身(例如,通过等待条件变量)。如果您需要线程B在设置标志时立即停止它正在做的任何事情,那么很抱歉,您需要一个不同的体系结构,因为Java线程不是这样工作的。