# Odd Even number synchronization in threads

• 03-10-2009, 01:28 PM
DukeNukem
Odd Even number synchronization in threads
Hi All,

This is my first post and I could not find any solution to the thread concurrency problem I want to solve.

I want to write code where one thread outputs odd number and another outputs even number is proper ascending order. For ex, 1,2,3,4,5,6,7..

I have written the following code to solve the problem, if I print the numbers directly inside the synchronized method then the problem is solved. But how do I return the numbers in proper order, from the methods getOdd() & getEven() as a return parameter. Please help.

Code:

```import static java.lang.System.out; public class TestOddEven {   public static void main(String[] args) {         Q q = new Q();     Even even = new Even(q);     Odd odd = new Odd(q);       }   } class Q {     boolean isOdd = false;   int i = 0;     synchronized int getOdd() {         while(!isOdd) {       try {         wait();       } catch(InterruptedException e) {}     }     isOdd = false;     //System.out.println("Odd = = " + i++);     notifyAll();         return i++;   }   synchronized int getEven() {         while(isOdd) {       try {         wait();       } catch(InterruptedException e) {}     }     isOdd = true;     //System.out.println("Even = = " + i++);     notifyAll();     return i++;   } } class Odd implements Runnable {   Q q;   Thread t;     Odd(Q q) {     this.q = q;     t = new Thread(this," --Odd-- ");     t.start();   }     public void run() {     for(int i=0;i<10;i++)       System.out.println("Odd === "+q.getOdd());     System.out.println("-- End thread Odd --");   }   } class Even implements Runnable {   Q q;   Thread t;     Even(Q q) {     this.q = q;     t = new Thread(this," --Even-- ");     t.start();   }     public void run() {     for(int i=0;i<10;i++)       System.out.println("Even ==="+q.getEven());         System.out.println("-- End thread Even --");   }   }```
• 03-16-2009, 03:02 PM
Steve11235
Sounds like a homework problem, so I don't want to give too much...

You have a lot of code to do a simple task. Basically, you have two threads that do essentially the same task, which is to start at a certain value, print it, and then add 2. The threads should wait on each other.

You need one class that accepts three parms: a start point and an object to wait on, and an object to notify. Start the threads, each waiting on its own object. Have the main notify on the odd thread object. When each thread loops, it should notify the other thread's object. Throw in a Thread.wait(15) before notifying, to avoid a race condition.