Friday, July 18, 2014

Thread synchronization Example

Problem statement

Two threads, one has to print odd numbers and another has to print even no. Start both the threads. They have to print odd and even numbers in order 1,2,3,4,5,6,7,8,...

public class Main {

  public static int counter = 1;
  
  public static void main(String[] args) {
    Main main = new Main();
    Thread odd = new Thread(new EvenOddThread(main,false),"Odd Thread");
    Thread even = new Thread(new EvenOddThread(main,true), "Even Thread");
    
    odd.start();  
    even.start();
  }
}

class EvenOddThread implements Runnable {

  Object syc;
  boolean isEven;

  public EvenOddThread(Object sync,boolean isEven) {
    this.syc = sync;  
    this.isEven = isEven;
  }

  public void run() {
    for (int i = 1; i < 50; i = i + 1) {
      synchronized (this.syc) {
        try {
          
          if(isEven && Main.counter%2 == 0){
            System.out.println(Thread.currentThread().getName() +" - "+  Main.counter++);
            syc.notifyAll();
          }else if (isEven && Main.counter%2 != 0){
            syc.wait();
          }else if(!isEven && Main.counter%2 == 0){
            syc.wait();
          }else if (!isEven && Main.counter%2 != 0){
            System.out.println(Thread.currentThread().getName() +" - "+  Main.counter++);
            syc.notifyAll();
          }
          
        } catch (InterruptedException e) {
          e.printStackTrace();
        }

      }
    }
  }  
  
}

No comments:

Post a Comment