Thursday, April 30, 2009

print odd and even numbers by two different threads in java

/**
* prints numbers starting from 0 to 10
* even thread prints 0,2,4,6...
* odd thread print 1,3,5,7....
* such that output comes as 0 1 2 3 4 5 6 7....
* @author satish
*
*/
public class OddEvenThread {


public static void main(String[] args)
{
invokeThread();
}

/**
* invokes even and odd printing threads
*
*/
private static void invokeThread()
{
Counter l_count = new Counter();

EvenPrint evenThread = new EvenPrint(l_count);
Thread eventhread = new Thread(evenThread);
eventhread.start();

OddPrint oddThread = new OddPrint(l_count);
Thread oddthread = new Thread(oddThread);
oddthread.start();

}

}


class EvenPrint implements Runnable
{
private Counter m_Count;
private int upperLimit;

EvenPrint(Counter count)
{
m_Count = count;
upperLimit = 10;
}

public void run() {

for(int i = 0; i<= upperLimit;i++)
{
m_Count.printEven();
}
}

}

class OddPrint implements Runnable
{
private Counter m_Count;
private int upperLimit;

OddPrint(Counter counter)
{
m_Count = counter;
upperLimit = 10;
}

public void run() {

for(int i = 0; i<= upperLimit;i++)
{
m_Count.printOdd();
}
}

}

class Counter
{
private int counter;
private boolean turn;

Counter()
{
counter = 0;
turn = true;
}

public synchronized void printEven()
{
if(turn == false)
{
try {
wait();
} catch (InterruptedException e) {

e.printStackTrace();
}
}
else
{
System.out.println("even " + counter);
counter++;
turn = false;
notify();
}
}

public synchronized void printOdd()
{
if(turn == true)
{
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
else
{
System.out.println("odd " + counter);
counter++;
turn = true;
notify();
}
}
}