【问题标题】:Stop thread from inside and notify from outside从内部停止线程并从外部通知
【发布时间】:2023-04-09 09:12:02
【问题描述】:

这是我想做的基本概念

假设我有一个看起来像这样的线程。

public class Thread1 implements Runnable{

    run(){

        while(true){
       //doWork and have thread 2 start working over a TCP connection, in my particular case
       wait();
   }

}

还有线程 2

 public class Thread2 implements Runnable{

    run(){

       while(true){
       //doWork and now I need to wake up thread 1
       t1.notify(); //???
    }

}

这显然行不通...我的问题是如何使这项工作基本完成。两个线程都是在 main 中创建的,所以我可以给他们任何必要的信息。 任何帮助将不胜感激。

【问题讨论】:

    标签: java multithreading wait notify


    【解决方案1】:

    我能想到几个学派:

    第一个是有 2 个线程,如您的示例所示。它们可以共享几种类型的对象,thread2 可以通过这些对象通知thread1

    使用java.util.concurrent.Condition

    // thread1
    public void run() {
        // to wait
        lock.lock();
        try {
            condition.await();
        } finally {
            lock.unlock();
        }
    }
    
    //thread2
    public void run() {
        // to notify
        lock.lock();
        try {
            condition.signal();
        } finally {
            lock.unlock();
        }
    }
    

    您也可以使用CyclicBarrier,也许还有其他类型。

    第二种思路是拥有一个工作线程,使用ExecutorService执行另一个工作线程:

    // thread2
    public void run() {
        executorService.execute(new RunnableThread1());
    }
    

    这个概念将 thread1 完成的工作视为可以多次执行的独立任务。所以这可能与您的程序不兼容。

    最后一个选项是使用Thread.interrupt

    //thread1
    public void run() {
        while (true) {
             try {
                 Thread.sleep(sleepTime);
             } catch(InterruptedException e) {
                 // signaled.
             }
        }
    }
    
    //thread 2
    public void run() {
        thread1.interrupt();
    }
    

    这可能有点问题,因为中断调用最好用于停止线程而不是向它们发出信号。

    【讨论】:

    • 解释得很好。谢谢
    猜你喜欢
    • 1970-01-01
    • 2021-04-03
    • 2017-05-31
    • 1970-01-01
    • 2015-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多