synchronized returnType methodName(parameters)
{
// method body
}
class BookMovieSeat
{
int total_seats=10;
synchronized void bookSeat(int seats, String name)
{
if(total_seats>=seats)
{
System.out.println(name+" booked "+seats+" seats successfully");
total_seats=total_seats-seats;
System.out.println("Total seats left : "+total_seats);
}
else
{
System.err.println(name+" sorry...!! seats not left");
System.err.println("Total seats left : "+total_seats);
}
}
}
class MyThread extends Thread
{
BookMovieSeat bts;
int seats;
public MyThread(BookMovieSeat bts, int seats)
{
this.bts=bts;
this.seats=seats;
}
public void run()
{
bts.bookSeat(seats, Thread.currentThread().getName());
}
}
public class MovieBookingApp
{
public static void main(String[] args)
{
BookMovieSeat bts=new BookMovieSeat();
MyThread deepak=new MyThread(bts, 6);
deepak.setName("Deepak");
deepak.start();
MyThread amit=new MyThread(bts, 5);
amit.setName("Amit");
amit.start();
}
}
Deepak booked 6 seats successfully Total seats left : 4 Amit sorry...!! seats not left Total seats left : 4
bookSeat()
is a synchronized method,
so only one thread can book seats at a time on the same
BookMovieSeat
object (bts
).
bookSeat()
.
bookSeat()
, and check the
updated total_seats
.
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
We’re here to make our tutorials better based on your thoughts and suggestions.