Friday, 23 June 2017

Using synchronized blocks with Threads ~ foundjava

Offer : Now get Mac OS X version 10.6.3 Snow Leopard for 36/- only. Check it out.

Synchronized block is one of the way of approach of synchronizing threads.
class FirstSync
{
    public void printHelloWorld()
    {
    synchronized(this)
    {
        try

        {
        System.out.print("Hello");
        Thread.sleep(1000);
        }catch(InterruptedException e){
        System.out.println("First sync interrupted.");      
        }
        System.out.print(" World. ");
    }
    }
}
class SecondSync
{
    public void printMe()
    {
    synchronized(this)
    {
        try
        {
        System.out.print("I am a ");
        Thread.sleep(1000);
        }catch(InterruptedException e){
        System.out.println("Second sync interrupted.");
        }
        System.out.println("sync method");
    }
    }
}
class SyncBlockDemo
{
    public static void main(String args[])
    {
    // Get current thread's object
    Thread mainThread=Thread.currentThread();
  
    // Set a name to main thread
    mainThread.setName("Main Thread");
  
        new Thread(new Runnable(){
            public void run()
            {
            // Create thread objects
            FirstSync f=new FirstSync();
            f.printHelloWorld();
            SecondSync s=new SecondSync();
            s.printMe();
            }
        }).start();

    }
}
-----------------------------------------
 Output :
-----------------------------------------
Hello World. I am a sync method

No comments:

Post a Comment