-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHappyBus.java
More file actions
62 lines (46 loc) · 1.6 KB
/
HappyBus.java
File metadata and controls
62 lines (46 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import java.util.*;
import java.io.*;
class HappyBus{
public static void main(String[] args){
BusReservation br = new BusReservation();
PassengerThread pt1 = new PassengerThread(2,br,"SAM");
PassengerThread pt2 = new PassengerThread(2, br, "Jack");
pt1.start();
pt2.start();
}
}
class BusReservation implements Runnable{
private int totalSeatsAvailable=2;
public void run() {
//BusReservation br = new BusReservation();
PassengerThread pt = (PassengerThread) Thread.currentThread();
boolean ticketsBooked = this.bookTickets(pt.getSeatsNeeded(), pt.getName());
if(ticketsBooked==true){
System.out.println("CONGRATS"+Thread.currentThread().getName()+" .. The number of seats requested("+pt.getSeatsNeeded()+") are BOOKED");
}else{
System.out.println("Sorry Mr."+Thread.currentThread().getName()+" .. The number of seats requested("+pt.getSeatsNeeded()+") are not available");
}
}
public synchronized boolean bookTickets(int seats, String name){
System.out.println("Welcome to HappyBus "+Thread.currentThread().getName()+" Number of Tickets Available are:"+this.getTotalSeatsAvailable());
if (seats>this.getTotalSeatsAvailable()) {
return false;
} else {
totalSeatsAvailable = totalSeatsAvailable-seats;
return true;
}
}
private int getTotalSeatsAvailable() {
return totalSeatsAvailable;
}
}
class PassengerThread extends Thread{
private int seatsNeeded;
public PassengerThread(int seats, Runnable target, String name) {
super(target,name);
this.seatsNeeded = seats;
}
public int getSeatsNeeded() {
return seatsNeeded;
}
}