olá colegas…
eu gostaria de saber se é possível ter threads rodando outros threads?
tipo um thread pai tem n threads filhos
muito obrigada
olá colegas…
eu gostaria de saber se é possível ter threads rodando outros threads?
tipo um thread pai tem n threads filhos
muito obrigada
Sim, é só o objeto Runnable da Thread iniciar outras Threads…
Por exemplo:
public class Teste {
static class Task1 implements Runnable {
private int id;
public Task1(int id) {
this.id = id;
}
public void run() {
// executa 3 threads, cada uma executa a Task2.
Thread th1 = new Thread(new Task2(id, 1));
Thread th2 = new Thread(new Task2(id, 2));
Thread th3 = new Thread(new Task2(id, 3));
th1.start();
th2.start();
th3.start();
}
}
static class Task2 implements Runnable {
private int id1;
private int id2;
public Task2(int id1, int id2) {
this.id1 = id1;
this.id2 = id2;
}
public void run() {
// faz algo
try {
Thread.sleep(Double.valueOf(Math.random() * 300).longValue());
} catch (InterruptedException e) {
}
System.out.println("thread principal: " + id1 + " filha: " + id2);
}
}
public static void main(String[] args) {
// executa 3 threads, cada uma executa a Task1 que por sua vez executa
// mais 3
Thread tp1 = new Thread(new Task1(1));
Thread tp2 = new Thread(new Task1(2));
Thread tp3 = new Thread(new Task1(3));
tp1.start();
tp2.start();
tp3.start();
}
}
muito obrigada colega
ateh mais