【发布时间】:2013-12-12 22:03:15
【问题描述】:
我有多个类型的多个线程(不同的类)。我希望以防其中一个抛出异常并被另一个新线程替换。我知道连接线程功能,但是我将如何为 5 种不同类型的线程实现它们,例如如果类型 1 线程死亡立即被替换,而不必等待类型 2 首先死亡。
这是一些示例伪代码。
class1 implements runnable{
void run(){
try{
while(true){
repeat task
}
} catch(Exception e){
log error
}
}
}
class2 implements runnable{
void run(){
try{
while(true){
repeat task
}
} catch(Exception e){
log error
}
}
}
class3 implements runnable{
void run(){
try{
while(true){
repeat task
}
} catch(Exception e){
log error
}
}
}
public main(){
// start all threads .start()
}
【问题讨论】:
-
不要子类化 Thread,实现 Runnables 并使用 Executor 执行它们(参见 Executors)。
-
@isnot2bad,我很难理解你的意思。能给我举个例子吗?
-
您能否添加一些代码,以便我们知道线程在其运行方法中正在做什么?他们为什么会“死”,死后会发生什么。
-
@isnot2bad 我进行了编辑。请检查一下。
-
在这个时代,管理自己的线程太辛苦了。看看akka.io 什么的。让框架来管理线程并专注于您的任务。
标签: java multithreading