从内部停止线程,从外部通知

问题描述 投票:1回答:2

这是我想做的基本概念。

比如说我的线程一是这样的。

public class Thread1 implements Runnable{

    run(){

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

}

而第二条线

 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
2个回答
1
投票

我可以想到几种思路。

第一种是像你的例子一样,有两个线程。它们可以共享几种类型的对象,通过这些对象 螺纹2 可以通知 螺纹1.

使用 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());
}

这一概念着眼于以下方面所做的工作: 螺纹1 作为一个独立的任务,可以多次执行。所以这可能与你的程序不兼容。

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

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

//thread 2
public void run() {
    thread1.interrupt();
}

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

© www.soinside.com 2019 - 2024. All rights reserved.