* Print even/odd numbers sequentially using two different threads
*/
public class ThreadSequence {
public static ThreadSequence tdSeq = new ThreadSequence();
boolean avail = true;
public ThreadSequence() {
}
public static void main(String[] args) {
Thread one = new Thread(new MyThreadOdd());
Thread two = new Thread(new MyThreadEven());
two.start();
one.start();
}
}
class MyThreadOdd implements Runnable {
public void run() {
for (int i = 1; i <= 20; i += 2)
{
synchronized (ThreadSequence.tdSeq) {
while (ThreadSequence.tdSeq.avail == false) {
try {
ThreadSequence.tdSeq.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
ThreadSequence.tdSeq.avail = false;
System.out.println(this.getClass().getName() +" -> " +i);
ThreadSequence.tdSeq.avail = true;
ThreadSequence.tdSeq.notify();
}
}
}
}
class MyThreadEven implements Runnable {
public void run() {
for (int i = 0; i <= 20; i += 2)
{
synchronized (ThreadSequence.tdSeq) {
while (ThreadSequence.tdSeq.avail == false) {
try {
ThreadSequence.tdSeq.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ThreadSequence.tdSeq.avail = false;
System.out.println(this.getClass().getName()+" -> " + i);
ThreadSequence.tdSeq.avail = true;
ThreadSequence.tdSeq.notify();
}
}
}
}