Sleep() - main duvida

3 respostas
LPJava

ae pessoal pq o main so eh alcançado uma unica vez?

class Susp implements Runnable{
public void run(){
	for(int x=0;x<4;x++){
			
		System.out.println(Thread.currentThread().getName());
			try{
			Thread.sleep(1000);
		}catch(InterruptedException ex){}
		
	}
}
	public static void main(String args[]){
		Susp sp = new Susp();
			Thread t = new Thread(sp);
				t.setName("Camilo");
			Thread t1 = new Thread(sp);
				t1.setName("neto");
			t.start();		
		
		System.out.println(Thread.currentThread().getName());
		
			t1.start();
	}
}

:?: eu achava q ele seria exibido alternadamente…

3 Respostas

ViniGodoy

O método main faz o disparo das duas threads depois termina. Se você não quer que termine, teria que colocar o println() dentro de um for, igual você fez no Runnable. Mas faça isso depois de t1.start(), ou então a Thread t1 nunca iniciará.

LPJava

como assim?

ViniGodoy

O problema está no fato do seu método main terminar. Isso termina também com a main Thread. Para que o main fique imprimindo, você teria que fazer:

public static void main(String args[]){
   Susp sp = new Susp();
   Thread t = new Thread(sp);
   t.setName("Camilo");
   Thread t1 = new Thread(sp);
   t1.setName("neto");
   t.start();		
   t1.start();
 		
   for(int x=0;x&lt4; x++){
      System.out.println(Thread.currentThread().getName());
      try{
         Thread.sleep(1000);
      }catch(InterruptedException ex){}
   }
}
Criado 20 de fevereiro de 2007
Ultima resposta 20 de fev. de 2007
Respostas 3
Participantes 2