【问题标题】:How to send interrupt signal to a thread from other thread如何从其他线程向线程发送中断信号
【发布时间】:2018-04-17 07:15:15
【问题描述】:

假设我有两个线程使用同一类的实例,它充当监视器。例如 Thread1 和 Thread2 使用 ABC 'o' 类的相同实例。

现在在 ABC 类中有一个同步方法 doProcess() 被两个线程调用。我在 doProcess() 中有一些条件,因为第一个线程处于 wait() 状态。现在,当第二个线程进入 doProcess() 时,有一个条件告诉它终止整个处理过程。

一个解决方案是通知第一个线程并更新一些标志以告诉它不要再次阻塞并完成。

我在想什么,我可以从我的监控对象“o”(就像 notify 和 notifyAll)发送任何信号到所有等待的线程以中断和终止吗?

编辑的第一个解决方案:

    sync doProcess()
    {
        while( you are thread1 and !flag )
        {
           wait();  //line 3
        }
        if( you are thread2)
        {
           flag = true;
           notifyAll(); //can i send send any interrupt signal to terminate all threads in line 3 itself;
        }
    }

【问题讨论】:

  • 没有o.notify()如何通知第一个线程?
  • @user6690200 你是对的,通过监控对象通知。
  • 我的意思是,One solution is to notify....What I was thinking....有什么区别,你能加点代码解释一下吗?
  • @user6690200 看到我编辑的问题。

标签: java multithreading


【解决方案1】:

是的。方法是 .interrupt() 这将在接收线程中抛出 InterruptedException,这应该在 run() 方法中处理。 您仍然需要在正在运行的线程上设置标志,因为如果线程没有阻塞,则不会发生 InterruptedException。

【讨论】:

  • 为了调用 .interrupt() 我们需要那个特定线程的对象。但是我想在不知道有多少线程在等待的情况下向所有等待的线程发送信号,就像 notifyAll()
  • 是的,这是一种方法,但我不想知道活动线程。我正在寻找的东西,某种通过监视器的信号。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多