I have three threads ThreadA, ThreadB and ThreadC printing values A, B and C respectively in loop.
I want output to be like A,B,C and then again A, B and C till loops are executing in threads.I want to write this sample program using wait and notify. Below code is printing the desired output but sometimes I am just seeing "A" in output, I am not able to figure out the case.
public class ThreadOrder {
public static void main(String[] args) {
Object lockAB = new Object();
Object lockBC = new Object();
Object lockCA = new Object();
Thread threadA = new Thread(new ThreadOrder().new ThreadA(lockAB, lockCA));
Thread threadB = new Thread(new ThreadOrder().new ThreadB(lockAB, lockBC));
Thread threadC = new Thread(new ThreadOrder().new ThreadC(lockBC, lockCA));
threadA.start();
threadB.start();
threadC.start();
}
class ThreadA implements Runnable {
Object lockAB;
Object lockCA;
public ThreadA(Object lockAB, Object lockCA) {
this.lockAB = lockAB;
this.lockCA = lockCA;
}
@Override
public void run() {
for(int i=0; i<3; i++) {
if(i!=0) {
try {
synchronized (lockCA) {
lockCA.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("A");
synchronized (lockAB) {
lockAB.notify();
}
}
}
}
class ThreadB implements Runnable {
Object lockAB;
Object lockBC;
public ThreadB(Object lockAB, Object lockBC) {
this.lockAB = lockAB;
this.lockBC = lockBC;
}
@Override
public void run() {
for(int i=0; i<3; i++) {
try {
synchronized (lockAB) {
lockAB.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("B");
synchronized (lockBC) {
lockBC.notify();
}
}
}
}
class ThreadC implements Runnable {
Object lockBC;
Object lockCA;
public ThreadC(Object lockBC, Object lockCA) {
this.lockBC = lockBC;
this.lockCA = lockCA;
}
@Override
public void run() {
for(int i=0; i<3; i++) {
try {
synchronized (lockBC) {
lockBC.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("C");
synchronized (lockCA) {
lockCA.notify();
}
}
}
}
}