I would like for thread A to iterate once through the for loop, wait for thread B to loop once through the for loop and wait for thread C to loop once through the for loop. And then all over again. I tried to use wait() and notify() but I got nowhere. How could one solve the problem?
public class Test extends Thread {
static int counter=0;
synchronized public void run() {
for(int i=0; i<4; i++) {
System.out.println(Thread.currentThread().getName()+" "+counter++);
}
}
public static void main(String[] args) throws InterruptedException {
Test t1 = new Test();
Test t2 = new Test();
Test t3 = new Test();
t1.setName("A");
t2.setName("B");
t3.setName("C");
t1.start();
t2.start();
t3.start();
}
}
It should print the following to the console:
A 0
B 1
C 2
A 3
B 4
C 5
A 6
B 7
C 8
A 9
B 10
C 11
But using the code I get a random output like this:
A 0
A 3
A 4
A 5
C 2
C 6
C 7
B 1
C 8
B 9
B 10
B 11