Como colocar um thread em pausa - Thread.wait () / Thread.notify ()
Estou tentando entender como os threads funcionam e escrevi um exemplo simples em que quero criar e iniciar um novo thread, o thread, exibir os números de 1 a 1000 no thread principal, retomar o thread secundário e exibir os números de 1 a 1000 no segmento secundário. Quando deixo de fora o Thread.wait () / Thread.notify (), ele se comporta conforme o esperado, os dois threads exibem alguns números por vez. Quando adiciono essas funções, por algum motivo, os números da linha principal são impressos em segundo e não em primeiro. O que estou fazendo de errado
public class Main {
public class ExampleThread extends Thread {
public ExampleThread() {
System.out.println("ExampleThread's name is: " + this.getName());
}
@Override
public void run() {
for(int i = 1; i < 1000; i++) {
System.out.println(Thread.currentThread().getName());
System.out.println(i);
}
}
}
public static void main(String[] args) {
new Main().go();
}
public void go() {
Thread t = new ExampleThread();
t.start();
synchronized(t) {
try {
t.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for(int i = 1; i < 1000; i++) {
System.out.println(Thread.currentThread().getName());
System.out.println(i);
}
synchronized(t) {
t.notify();
}
}
}