00:00
/* N60mBA - synchronized for two object w/o using static */ /* 1. for class level 2. previous use for object */ class BookTheaterSeat{ int total_seats = 10; 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 N60mBA 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,6); t2.start(); BookTheaterSeat b2 = new BookTheaterSeat(); Mythread2 t3 = new Mythread2(b2,5); t3.start(); Mythread2 t4 = new Mythread2(b2,9); t4.start(); } } // data inconsistant raheyga sync. keyword ke bavjuud /* ramannegi@Ramans-MacBook-Pro x % javac N60mBA.java ramannegi@Ramans-MacBook-Pro x % java N60mBA 7 seats booked successfully 5 seats booked successfully seats left = 3 seats left = 5 sorry seats cannot be booked..!! sorry seats cannot be booked..!! seats left = 3 seats left = 5 */
Home PREVIOUS NEXT