A Developer Gateway To IT World...

Techie Uncle Software Testing Core Java Java Spring C Programming Operating System HTML 5 Java 8 ES6 Project

Use of Synchronized Keyword in Java:

It is used in multi-threaded environment so that one thread can enter in a particular block or in a method.

Keep in mind that synchronized is a modifier which is used before a block or a method, but not before class or variable.


program:

class Booking
{
    void checkAvaibility()
    {
        System.out.println("Two seats are available in Rajdhani Train.");
    }
    synchronized void getReservation() throws InterruptedException
    {
        System.out.println("success...");
    }
}

class Heera extends Thread
{
    Booking bk;
    Heera(Booking b)
    {
        this.bk=b;
    }
   
    @Override
    public void run()
    {
        System.out.println("Heera thread working Now:");
        for(int i=0; i<=2; i++)
        {
           
            bk.checkAvaibility();
            try
            {
                bk.getReservation();
            } catch (InterruptedException ex) {
              ex.printStackTrace();
            }
        }
    }
}

class Navneet extends Thread
{
    Booking bk;
    Navneet(Booking b)
    {
        this.bk=b;
    }
   
    @Override
    public void run()
    {
        System.out.println("Navneet thread working Now:");
        for(int i=0; i<=2; i++)
        {
           
            bk.checkAvaibility();
            try
            {
                bk.getReservation();
            } catch (InterruptedException ex){
                ex.printStackTrace();
            }
        }
}
}

public class TestSynch
{
    public static void main(String args[])
    {
        Booking  mybooking = new Booking();
        Heera h1=new Heera(mybooking);
        Navneet n1 = new Navneet(mybooking);
       
        h1.start();
        n1.start();
    }
}

LEARN TUTORIALS

.

.