Metodo join() threads

2 respostas
LPJava

ae pesoal uma duvida ontem na teoria do metodo join() a kathy diz q ele joga o thread atual para o final de outro thread? nao entendi… fiz um codigo para ver se seria isso… quem puder me dar uns toques ae fico agradecido…

class Joi implements Runnable{
	public void run(){
		//for(int x=1;x<10;x++)
		System.out.println("ainda vejo threads mortos " + Thread.currentThread().getName());
	}
}
class JoiTest{
	public static void main(String args[]){
		Joi j = new Joi();
		Thread th = new Thread(j);
		Thread th1 = new Thread(j);
		
		th.setName("join");
		
		th1.start();	
		th.start();
		
		try{
		th.join();
		//me pegue e coloque depois de th.
		//de forma que t precise finalizar antes que atual possa executar novamente
		}catch(InterruptedException a){}
	}
}
/* vamos analisar com cuidado:
peguei o th1 que tem jo*/

2 Respostas

Deh

Pesquisando eu achei esse código aqui, bem explicativo...
quando você da "Thread.join()" você tranca a thread atual(no caso do Exemplo o main), e ele só vai ser executado assim que as Threads filhas terminem sua execução... testa esse exemplo abaixo... acredito que ajude!

class Counter extends Thread {

	private int currentValue;

	public Counter(String threadName) {
		super(threadName); // (1) Initialize thread
		currentValue = 0;
		System.out.println(this);
		start(); // (2) Start this thread
	}

	public void run() { // (3) Override from superclass
		try {
			while (currentValue < 5) {
				System.out.println(getName() + ": " + (currentValue++));
				Thread.sleep(500); // (4) Current thread sleeps
			}
		} catch (InterruptedException e) {
			System.out.println(getName() + " interrupted.");
		}
		System.out.println("Exit from " + getName() + ".");
	}

	public int getValue() { return currentValue; }
}

public class AnotherClient {
	public static void main(String args[]) {

		Counter cA = new Counter("Counter A");
		Counter cB = new Counter("Counter B");

		try {
			System.out.println("Wait for the child threads to finish.");
			cA.join(); // (5)
			cB.join(); // (6)
			System.out.println("fsdfsdfsdfsdf");
			if (!cA.isAlive()) // (7)
				System.out.println("Counter A not alive.");
			if (!cB.isAlive()) // (8)
				System.out.println("Counter B not alive.");
		} catch (InterruptedException e) {
			System.out.println("Main Thread interrupted.");
		}
		System.out.println("Exit from Main Thread.");
	}
}
LPJava

po valeu… eu dei uma pesquisada tb e achei essa aula… que ta ajudando bastante… galera valeu ai pelas dicas… ehhe vou tentar ver se pego essas implementações certas dos metodos… ainda eh meio confuso.

http://www.javafree.org/javabb/viewtopic.jbb?t=6955

Criado 12 de janeiro de 2007
Ultima resposta 12 de jan. de 2007
Respostas 2
Participantes 2