synchronized(objectReference)
block to lock only those lines.
// Synchronizing on current object
synchronized (this)
{
// Critical section code
}
// Synchronizing on a specific object
synchronized (objectReference)
{
// Critical section code
}
Note:
class BookMovieSeat
{
int total_seats = 10;
void bookSeat(int seats, String name)
{
// Some lines of code which are not synchronized (can run concurrently)
synchronized (this) // synchronized block
{
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);
}
}
// Some lines of code which are not synchronized (can run concurrently)
}
}
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()
method
instead of making the whole method synchronized.
total_seats
)
is synchronized, not the entire method.
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.