00:00
N61mBA.png
/* N61mBA - synchronized for two object using static */ /* 1. for class level 2. previous use for object 3. yaha par t1 t2 t3 t4 sabhe ek saath accese na kare isleaye static keyword ka use 4. static class par lock aquare karne me use hota hai 5. sabhee thD ek ek karke lock aquare karege 6. class ka bhee apna ek lock hota hai */ class BookTheaterSeat{ static int total_seats = 10; static synchronized void bookSeat(int seats){ 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); } } } class Mythread1 extends Thread{ BookTheaterSeat b ; int seats ; Mythread1 (BookTheaterSeat b, int seats){ this.b = b; this.seats=seats; } public void run(){ b.bookSeat(seats); } } class Mythread2 extends Thread{ BookTheaterSeat b ; int seats ; Mythread2 (BookTheaterSeat b, int seats){ this.b = b; this.seats=seats; } public void run(){ b.bookSeat(seats); } } public class N61mBA extends Thread{ public static void main(String[] args) { BookTheaterSeat b1 = new BookTheaterSeat(); Mythread1 t1 = new Mythread1(b1,7); t1.start(); Mythread1 t2 = new Mythread1(b1,2); t2.start(); BookTheaterSeat b2 = new BookTheaterSeat(); Mythread2 t3 = new Mythread2(b2,5); t3.start(); Mythread2 t4 = new Mythread2(b2,9); t4.start(); } } /* ramannegi@Ramans-MacBook-Pro x % javac N61mBA.java ramannegi@Ramans-MacBook-Pro x % java N61mBA 7 seats booked successfully seats left = 3 sorry seats cannot be booked..!! seats left = 3 sorry seats cannot be booked..!! seats left = 3 2 seats booked successfully seats left = 1 */
Home PREVIOUS NEXT