thread
(or request handler).
Thread-1
) and Amit (Thread-2
), both click “Book Movie” at the same time:
threads
check → seat available → both book successfully.
threads
are allowed to enter the critical section simultaneously.
class BookMovieSeat
{
int total_seats=10;
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 booked 5 seats successfully Total seats left : -1
wait()
, notify()
and notifyAll()
.
synchronized
Methodsynchronized
Blockstatic synchronized
Method (Static Synchronization)ReentrantLock
(from java.util.concurrent.locks
)wait()
– makes a thread wait until notified.notify()
– wakes up a single waiting thread.notifyAll()
– wakes up all waiting threads.
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.