Threads em Java

Olá pessoal.

Estou tentando “bolar” um esquema para aprender Threads em Java mais facilmente. Seguindo os códigos, o que acontece é que o “print” do laço está saindo fora de ordem.
Alguém poderia me ajudar com um simples tutorial?
Segue:

package br.com.ricardo001;

public class Tes0006 implements Runnable {
	private Thread t01;

	public void start(String cStr) {
		if (t01 == null) {
			System.out.println(this);
			t01 = new Thread(this, cStr);
			t01.start();
		}
	}

	@Override
	public synchronized void run() {
		Thread myThread = Thread.currentThread();
		while (t01 == myThread) {
			for (int i = 0; i < 50; i++) {
				System.out.println(i + " " + t01.getName());
				System.out.println("DONE! " + t01.getName());
			}
			t01 = null;
		}
	}
}
package br.com.ricardo001;

public class Tes0006T {
	public static void main(String[] args) {
		Tes0006 t001 = new Tes0006();
		t001.start("Thread 1");
		Tes0006 t002 = new Tes0006();
		t002.start("Thread 2");
		Tes0006 t003 = new Tes0006();
		t003.start("Thread 3");
		Runnable t004 = new Tes0006();
		t004.run();
	}
}

Bom, depois do “t01.start();”, coloquei o trecho de código abaixo e funcionou direitinho:

		try {
			t01.join();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

Agora vamos aprimorar esse código tosco rssss.

1 curtida