Thread Synchronization using synchronized blocks


In the previous example the Shared class provides synchronized method for threads. Threads do nothing so if share class removes the synchronized then thread object will not be able to access the print method synchronously.
            There is second mechanism by which the thread can provided the synchronization to the any object or block.
class MyThread1 extends Thread
{    
    Shared s;
    MyThread1(Shared s)
    {
        this.s=s;
    }    
    public void run()
    {    
        synchronized(s)
        {
            s.print();
        }
    }
}
class MyThread2 extends Thread
{    
    Shared s;
    MyThread2(Shared s)
    {
        this.s=s;
    }    

    public void run()
    {    
        synchronized(s)
        {
            s.print();
        }
    }
}

class syn
{
    public static void main(String ar[])
    {
        Shared obj=new Shared();
        MyThread1 t1=new MyThread1(obj);
        MyThread2 t2=new MyThread2(obj);
        t1.start();
        t2.start();
    }
}

class Shared
{
    public  void print()
    {
         System.out.print("< Hi ");
         try{Thread.sleep(1000);}catch(InterruptedException e){}
         System.out.print(" Hello >\n");
    }
}
==================================================================================
/OUTPUT
 < Hi  Hello >
 < Hi  Hello >
 */

No comments:

Popular Posts