1. Métodos para verificar se uma thread terminou:
isAlive()
- Retorna true se a thread ainda estiver em execução; caso contrário, retorna false.
- Usado para verificar continuamente o estado de threads.
join()
- Faz com que a thread que chamou o método espere até que a thread especificada termine.
- Existem variações que permitem definir um tempo máximo de espera.
2. Exemplo usando isAlive():
// Verifica se as threads estão vivas
class MyThread implements Runnable {
Thread thrd;
MyThread(String name) {
thrd = new Thread(this, name);
thrd.start(); // Inicia a thread
}
public void run() {
System.out.println(thrd.getName() + " starting.");
try {
for (int count = 0; count < 10; count++) {
Thread.sleep(400); // Suspende a execução por 400ms
System.out.println("In " + thrd.getName() + ", count is " + count);
}
} catch (InterruptedException exc) {
System.out.println(thrd.getName() + " interrupted.");
}
System.out.println(thrd.getName() + " terminating.");
}
}
class MoreThreads {
public static void main(String[] args) {
System.out.println("Main thread starting.");
MyThread mt1 = new MyThread("Child #1");
MyThread mt2 = new MyThread("Child #2");
MyThread mt3 = new MyThread("Child #3");
// Verifica se as threads ainda estão vivas
do {
System.out.print(".");
try {
Thread.sleep(100);
} catch (InterruptedException exc) {
System.out.println("Main thread interrupted.");
}
} while (mt1.thrd.isAlive() || mt2.thrd.isAlive() || mt3.thrd.isAlive());
System.out.println("Main thread ending.");
}
}
Pontos importantes:
- A thread principal verifica continuamente com isAlive() até que todas as threads filhas terminem.
- A execução das threads é agendada pelo Java, então a saída exata pode variar.
3. Exemplo usando join():
// Aguarda o término das threads com join()
class MyThread implements Runnable {
Thread thrd;
MyThread(String name) {
thrd = new Thread(this, name);
thrd.start(); // Inicia a thread
}
public void run() {
System.out.println(thrd.getName() + " starting.");
try {
for (int count = 0; count < 10; count++) {
Thread.sleep(400); // Suspende a execução por 400ms
System.out.println("In " + thrd.getName() + ", count is " + count);
}
} catch (InterruptedException exc) {
System.out.println(thrd.getName() + " interrupted.");
}
System.out.println(thrd.getName() + " terminating.");
}
}
class JoinThreads {
public static void main(String[] args) {
System.out.println("Main thread starting.");
MyThread mt1 = new MyThread("Child #1");
MyThread mt2 = new MyThread("Child #2");
MyThread mt3 = new MyThread("Child #3");
try {
mt1.thrd.join(); // Aguarda Child #1 terminar
System.out.println("Child #1 joined.");
mt2.thrd.join(); // Aguarda Child #2 terminar
System.out.println("Child #2 joined.");
mt3.thrd.join(); // Aguarda Child #3 terminar
System.out.println("Child #3 joined.");
} catch (InterruptedException exc) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread ending.");
}
}
Saída esperada (pode variar):
Main thread starting.
Child #1 starting.
Child #2 starting.
Child #3 starting.
In Child #1, count is 0
In Child #2, count is 0
In Child #3, count is 0
...
Child #1 terminating.
Child #1 joined.
Child #2 terminating.
Child #2 joined.
Child #3 terminating.
Child #3 joined.
Main thread ending.
Pontos importantes:
- join() garante que a thread principal só continue após a conclusão das threads filhas.
- A saída mostra o encerramento de cada thread na ordem esperada.
Top comments (0)