Olá pessoal,
Eu fiz um exemplo para testar ThreadGroup mas não entendi a saída. No código abaixo 3 threads do mesmo ThreadGroup começam a executar o método run então eu uso o método interrupt no grupo e todas threads são interrompidas e é executado o código do catch, mas não entendo porque depois de executar o que está dentro do catch é executado o println fora do catch já que as threads foram interrompidas:
class RunnableDeDestino implements Runnable{
public void run(){
try{
Thread.sleep(3000);
}catch(InterruptedException e){
System.out.printf("thread " + Thread.currentThread().getName() + " interrompida %n");
}
System.out.printf("executando " + Thread.currentThread().getName() + "... %n"); //PENSEI QUE ESSA LINHA NÃO SERIA EXECUTADA NENHUMA VEZ
}
}
public class GruposDeThreads {
public static void main(String[] args){
ThreadGroup tg = new ThreadGroup("grupo");
RunnableDeDestino destino = new RunnableDeDestino();
new Thread(tg, destino, "Thread 1").start();
new Thread(tg, destino, "Thread 2").start();
new Thread(tg, destino, "Thread 3").start();
tg.interrupt();
}
}
saída:
thread Thread 1 interrompida
thread Thread 2 interrompida
thread Thread 3 interrompida
executando Thread 2...
executando Thread 1...
executando Thread 3...