Java-Synchronization(Example Two)

Program : without Synchronization

final

Program : with Synchronization

final

Program Source : without Synchronization

class TicketCounter{
   
    int availableSeats = 2;
    
    void bookTicket(String pname,int numberOfSeats)
    {
        if((availableSeats>=numberOfSeats)&&(numberOfSeats>0))
        {
            System.out.println(pname+" : "+numberOfSeats+" Seats Booking Success");
            availableSeats-=numberOfSeats;
        }else
            System.out.println(pname+" : Seats Not Available");
    }
}

class TicketBookingThread extends Thread{

    TicketCounter tc;
    String name;
    int seats;
    
    TicketBookingThread(TicketCounter t,String pname,int pseats)
    {
        tc = t;
        name = pname;
        seats = pseats;
        start();
    }

    public void run()
    {
        tc.bookTicket(name, seats);
    }
}

public class Javaapp {

    public static void main(String[] args) {
    
        TicketCounter tc = new TicketCounter();
        TicketBookingThread th1 = new TicketBookingThread(tc,"Kannan",2);
        TicketBookingThread th2 = new TicketBookingThread(tc,"Sarava",2);
    }
}

Program Source : with Synchronization

class TicketCounter{
   
    int availableSeats = 2;
    
    synchronized void bookTicket(String pname,int numberOfSeats)
    {
        if((availableSeats>=numberOfSeats)&&(numberOfSeats>0))
        {
            System.out.println(pname+" : "+numberOfSeats+" Seats Booking Success");
            availableSeats-=numberOfSeats;
        }else
            System.out.println(pname+" : Seats Not Available");
    }
}

class TicketBookingThread extends Thread{

    TicketCounter tc;
    String name;
    int seats;
    
    TicketBookingThread(TicketCounter t,String pname,int pseats)
    {
        tc = t;
        name = pname;
        seats = pseats;
        start();
    }

    public void run()
    {
        tc.bookTicket(name, seats);
    }
}

public class Javaapp {

    public static void main(String[] args) {
    
        TicketCounter tc = new TicketCounter();
        TicketBookingThread th1 = new TicketBookingThread(tc,"Kannan",2);
        TicketBookingThread th2 = new TicketBookingThread(tc,"Sarava",2);
    }
}

Leave a Comment