从内部停止线程并从外部通知
Stop thread from inside and notify from outside
这是我想做的事情的基本概念
假设我有一个看起来像这样的线程。
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 中创建的,因此我可以为它们提供彼此所需的任何信息。
任何帮助将不胜感激。
我能想到几个学派:
第一个是有 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();
}
这可能有点问题,因为中断调用最好用于停止线程而不是向它们发出信号。
这是我想做的事情的基本概念
假设我有一个看起来像这样的线程。
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 中创建的,因此我可以为它们提供彼此所需的任何信息。 任何帮助将不胜感激。
我能想到几个学派:
第一个是有 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();
}
这可能有点问题,因为中断调用最好用于停止线程而不是向它们发出信号。