请帮我解决这个问题 主线程/父线程将触发子线程。如果我们要停止父/主线程,它还必须停止所有子/子线程
我想用中断做但不能做到 请帮我解决代码
以及如何确保所有子线程都已停止?是否有任何方法可以执行此操作
提前致谢!
我正在尝试做这样的事情:
public class ThreadTest1 extends Thread { private static final Logger 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());
}
}
答案 0 :(得分:1)
Java自动对线程进行分组。如果您没有定义特定的ThreadGroup, 它将始终分组为初始化发生的线程的子级。
因此,如果您中止父线程,它的所有childThreads也将被中止。
或许这可能会有所帮助(对不起,这是德语):dpunkt programming pdf