Monday, August 26, 2013

Java: Thread program to demonstrate wait and notify

Below question was asked to one of my friend during interview:

Write program to create 2 Threads "Jack" and "Jill". You write a program which will print " Jack Jill Jack Jill"
Thread execution:  Thread1, Thread2, again Thread2, then Thread2.


I tried to write program for above problem :
T1. Java:


public class T1 implements Runnable {
private static int count = 0;
public synchronized void run() {
int threadCount = 0;
while (true) {
count++;
threadCount = count;
System.out.println(Thread.currentThread().getName());

try {

notifyAll();
while (threadCount >= count) {
wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}

// If you comment below if block, Jack , jill threads will run
// forever one after another.
// So added to check if Jack and Jill threads run one after another
// 2 times
if (count >= 4) {
count++;
System.out.println(Thread.currentThread().getName() + " End");
notifyAll();
break;
}
}

}
public static void main(String[] args) {
T1 t = new T1();
Thread t1 = new Thread(t, "Jack");
Thread t2 = new Thread(t , "Jill");
t1.start();
t2.start();
}

}


Output:

Jack
Jill
Jack
Jill
Jack End
Jill End