Class object, not the instance, so it applies to
all objects of that class.
synchronized static method, other threads are
blocked from executing any other synchronized static method of the same class.
class MyClass
{
static synchronized void myMethod()
{
// code
}
}
class BookMovieSeat
{
static int total_seats = 10;
static 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 bms1 = new BookMovieSeat();
MyThread deepak = new MyThread(bms1, 6);
deepak.setName("Deepak");
deepak.start();
BookMovieSeat bms2 = new BookMovieSeat();
MyThread amit = new MyThread(bms2, 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(), which locks the class object
BookMovieSeat.class instead of individual instances.
total_seats variable is static, so it is
shared among all instances of the class.
bms1 and bms2),
only one thread at a time can execute the static synchronized method
for the class, ensuring thread safety.
bookSeat(),
Amit thread must wait until Deepak releases the
class-level lock.
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.