Using synchronized blocks with Threads

Synchronized block is one of the way of approach of synchronizing threads.

SyncBlockDemo.java

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

ధన్యవాదాలు (Thanks)