00:00
N59mBA.png
/* N59mBA - synchronized block */ /* 1. agar resource me keywal kuch part par he sync lagana hai to sync. block ka use karege jisse wo speed badeygee project ki 2. syntax synchronized(object reference expression) */ class BookTheaterSeat{ int total_seats = 10; void bookSeat(int seats){ System.out.println(Thread.currentThread().getName()); System.out.println(Thread.currentThread().getName()); System.out.println(Thread.currentThread().getName()); System.out.println(Thread.currentThread().getName()); System.out.println(Thread.currentThread().getName()); System.out.println(Thread.currentThread().getName()); synchronized(this){ if(total_seats>=seats){ System.out.println(seats+" seats booked successfully"); total_seats=total_seats-seats; System.out.println("seats left = " + total_seats); } else{ System.out.println("sorry seats cannot be booked..!!"); System.out.println("seats left = "+total_seats); } } System.out.println(Thread.currentThread().getName()); System.out.println(Thread.currentThread().getName()); System.out.println(Thread.currentThread().getName()); System.out.println(Thread.currentThread().getName()); System.out.println(Thread.currentThread().getName()); System.out.println(Thread.currentThread().getName()); System.out.println(Thread.currentThread().getName()); } } public class N59mBA extends Thread{ static BookTheaterSeat b; int seats; public void run(){ b.bookSeat(seats); } public static void main(String[] args) { b = new BookTheaterSeat(); N59mBA rajat = new N59mBA(); rajat.seats=7; rajat.start(); N59mBA amit = new N59mBA(); amit.seats=6; amit.start(); } } // both thread start simultaneously but one aquare lock of the object /* ramannegi@Ramans-MacBook-Pro x % javac N59mBA.java ramannegi@Ramans-MacBook-Pro x % java N59mBA Thread-0 Thread-0 Thread-0 Thread-0 Thread-0 Thread-0 Thread-1 Thread-1 Thread-1 Thread-1 Thread-1 Thread-1 7 seats booked successfully seats left = 3 Thread-0 Thread-0 Thread-0 Thread-0 Thread-0 Thread-0 Thread-0 sorry seats cannot be booked..!! seats left = 3 Thread-1 Thread-1 Thread-1 Thread-1 Thread-1 Thread-1 Thread-1 */
Home PREVIOUS NEXT