I want the threads to print out their name in order. The ouput should look something like this:
Thread-0
Thread-1
Thread-2
Thread-3
Thread-4
Thread-5
Thread-1
Thread-2
Thread-3
public class NameOutput extends Thread {
static final int N = 5;
static int activeThread = 0;
public static void main(String[] args){
for (int i = 1; i <= N; i++) {
new NameOutput().start();
}
}
@Override
public void run(){
while(true){
this.printThreadName();
}
}
private synchronized void printThreadName(){
String threadName = "Thread-"+ activeThread;
//Check if thread is in the right order
if(!threadName.equals(this.getName())){
try{
wait();
}catch (InterruptedException e){
System.out.println(this.getName()+" was interrupted!");
}
}else{
System.out.println(this.getName());
activeThread = (activeThread + 1) % N;
notifyAll();
}
}
}
Somehow the output is if Thread-0 gets selected first just Thread-0. The programm stops after the first thread waits.