Monday, August 12, 2013

How to synchronize the threads using wait and notify ?

There are 2 threads running simultaneously.
   a)one thread printing... 2,4,6,8.....100
   b)and another thread printing.... 1,3,5,7.....99

You need to synchronize 2 threads such that.....The output will be....as following.
Should not use sleep to delay the threads.

1,2,3,4,.....................100

Code
------

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package javaimp;





/**
 *
 * @author Anilkumar
 */
class Common{
    
    int i = 1;
    public  synchronized void printEven(){
        //System.out.println(Thread.currentThread().getName());
        try{
           for(int i1 = 2;i1<=10000;){ 
            
            if(getI()== 0 ){   
                System.out.println(i1+Thread.currentThread().getName()+"fir");
                setI(1);
                notify();
            }else{
                wait();
                i1=i1-2;
             }
                i1 = i1+2;
           }
             
        }catch(Exception e ){
            
            
        }
       
    }
    public synchronized void printOdd(){
        //System.out.println(Thread.currentThread().getName());
        try{
            for(int i1 = 1;i1<=10000;){
                if(getI()== 1 ){   
                    System.out.println(i1+Thread.currentThread().getName()+"sec");
                    //System.out.println(getI());
                    setI(0);
                    notify();
                }else{
                   wait();
                   i1=i1-2;
                }
            
                i1 = i1+2;
           }
        }catch(Exception e ){
            
        }
        
       
    }
    private synchronized void setI(int i){
        this.i= i;
    }
    private int getI(){
        return this.i;
    }
    
}
class EvenThread implements Runnable{

    Common c = null;
    EvenThread(Common c ){
        this.c = c;
    }
    public void run() {
       
             c.printEven();   
           
    }
    
    
}

class OddThread implements Runnable{

    Common c = null;
    OddThread(Common c ){
        this.c = c;
    }
    public void run() {
     
            c.printOdd();
           

     
    }
    
    
}









public class JavaImp {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
     
        Common c = new Common();
        Thread t1 = new Thread(new EvenThread(c),"Even");
         
        Thread t2 = new Thread(new OddThread(c),"Odd");
         
         t1.start();
         t2.start();
    }

}

No comments:

Post a Comment