我有一个名为action()的方法,用于部署三个线程。每个已部署的线程或工作线程都基于布尔类型为true的单个实例变量落入while循环中,例如boolean doWork = true,每个线程将有一个while(doWork){}循环。是否有可能从Java中的工作者线程调用主线程?
当线程完成作业时,将doWork设置为false,以阻止所有线程循环。然后我想以某种方式让主线程调用action()方法来重新部署线程来完成另一项工作。 (如果我使用其中一个工作线程来调用action()方法,那么它是否正常?)一旦它调用action()方法并且不知何故死亡,工作线程会终止吗?
我限制比如将两个线程简单
感谢
class TestThreads{
boolean doWork = true;
void action(){
ThreadOne t1 = new ThreadOne();
ThreadTwo t2 = new ThreadTwo();
}
//innerclasses
class ThreadOne implements Runnable{
Thread trd1;
public ThreadOne(){//constructor
if(trd1 == null){
trd1 = new Thread(this);
trd1.start();
}
}
@Override
public void run(){
while(doWork){
//random condition
//would set doWork = false;
//stop all other threads
}
action();//is the method in the main class
}
}
class ThreadTwo implements Runnable{
Thread trd2;
public ThreadTwo(){//constroctor
if(trd2 == null){
trd2 = new Thread(this);
trd2.start();
}
}
@Override
public void run(){
while(doWork){
//random condition
//would set doWork = false;
//stop all other threads
}
action();//is the method in the main class
}
}
}
为什么不使用'ExecutorService'来设计类似于你正在做的事情? – Nim 2012-02-01 17:43:18
即使我已经对upvoted @Nim评论,让我重复一遍:看看这种类型的事情ExecutorService。 – user949300 2012-02-01 17:45:09
@Nim也许这会更好,如果你写了更多的细节的答案,因为它可能会感兴趣其他人 – 2012-02-01 17:45:50