请帮我解决这个问题 主线程/父线程将触发子线程。如果我们停止父/主线程,它也必须停止所有子/子线程
我想用中断来做到这一点,但无法做到 请帮我解决代码
如何确保所有子线程都已停止?是否有任何方法可以做到这一点
提前致谢!
我正在尝试做这样的事情:
公共(public)类ThreadTest1扩展Thread{ 私有(private)静态最终记录器 LOGGER = Logger.getLogger("mylogger");
public void run(){
for(int i=1;i<=5;i++){
try{
if (!Thread.currentThread().isInterrupted()) {
LOGGER.log(Level.SEVERE,"Sleeping...");
Thread.sleep(1000);
LOGGER.log(Level.SEVERE,"Processing");
System.out.println(Thread.currentThread().getId()+"Thread id: "+i);
}
else{
throw new InterruptedException();
}
}catch(InterruptedException e){
System.out.println(e);
LOGGER.log(Level.SEVERE,"Exception", e);
Thread.currentThread().interrupt();
}
}
}
public static void main(String args[]){
ThreadTest1 t1=new ThreadTest1();
ThreadTest1 t2=new ThreadTest1();
ThreadTest1 t3=new ThreadTest1();
System.out.println(t1.getId());
System.out.println(t2.getId());
System.out.println(t3.getId());
t1.start();
t2.start();
t3.start();
System.out.println("Do you want to kill all processes: Press any key to continue");
int s=0;
try {
s = System.in.read();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(s!=0){
t1.interrupt();
t2.interrupt();
t3.interrupt();
}
System.out.println(t1.isAlive());
}
}
最佳答案
Java 自动对线程进行分组。如果没有定义具体的ThreadGroup, 它将始终分组为发生初始化的线程的子级。
因此,如果您中止父线程,则其所有子线程也会中止。
也许这会有所帮助(抱歉,这是德语):dpunkt programming pdf
关于 java |如果父线程终止则终止所有子线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27372562/