-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTicketReservation.java
90 lines (79 loc) · 2.71 KB
/
TicketReservation.java
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;
public class TicketReservation implements Runnable{
static AtomicInteger tickets;
static ReentrantLock lock = new ReentrantLock();
String s;
TicketReservation(String s,AtomicInteger shared_memory){
this.s = s;
this.tickets = shared_memory;
}
@Override
public void run() {
System.out.println("New Customer : "+Thread.currentThread().getName());
criticalProcess();
}
static void criticalProcess(){
lock.lock();
register(2);
cancel(1);
lock.unlock();
}
public static void register(int n_ticket){
System.out.println("\nBuying new Ticket : "+Thread.currentThread().getName());
try{
lock.lock();
Thread.sleep(3000);
AtomicInteger t = new AtomicInteger(tickets.intValue());
if(t.addAndGet(-n_ticket)<0){
System.out.println("Required amount of tickets not available");
return;
}
tickets.addAndGet(-n_ticket);
}
catch(Exception e){
e.printStackTrace();
}
finally {
lock.unlock();
System.out.println(tickets+" tickets available");
}
}
public static void cancel(int n_ticket){
System.out.println("\nCancelling the ticket bought : "+Thread.currentThread().getName());
try{
lock.lock();
Thread.sleep(3000);
tickets.addAndGet(n_ticket);
}
catch(Exception e){
e.printStackTrace();
}
finally {
System.out.println("Tickets cancelled and bill refunded");
lock.unlock();
System.out.println(tickets+" tickets available");
}
}
}
class Test{
public static void main(String[] args) {
AtomicInteger shared_memory = new AtomicInteger(100);
int n_customers = 7;
int n_collectors = 5;
TicketReservation thread = new TicketReservation(" ",shared_memory);
allocateCounter(n_customers,n_collectors,thread);
}
static void allocateCounter(int n_customers,int n_collectors,Runnable run){
ExecutorService executor = Executors.newFixedThreadPool(n_collectors);
for(int i=0;i<n_customers;i++){
executor.execute(run);
}
executor.shutdown();
while(!executor.isTerminated()){}
System.out.println("\nFinished all threads");
}
}