-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathATMMachine.java
More file actions
45 lines (41 loc) · 1.45 KB
/
Copy pathATMMachine.java
File metadata and controls
45 lines (41 loc) · 1.45 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
// Copyright: Ganesh Samarthyam, 2016; www.codeops.tech
import java.util.concurrent.locks.*;
// Each Person is an independent thread; their access to the common resource
// (the ATM machine in this case) needs to be synchronized using a lock
class Person extends Thread {
private Lock machine;
public Person(Lock machine, String name) {
this.machine = machine;
this.setName(name);
this.start();
}
public void run() {
try {
System.out.println(getName() + " waiting to access an ATM machine");
machine.lock();
System.out.println(getName() + " is accessing an ATM machine");
Thread.sleep(1000); // simulate the time required for withdrawing amount
} catch(InterruptedException ie) {
System.err.println(ie);
}
finally {
System.out.println(getName() + " is done using the ATM machine");
machine.unlock();
}
}
}
// This class simulates a situation where only one ATM machine is available and
// and five people are waiting to access the machine. Since only one person can
// access an ATM machine at a given time, others wait for their turn
class ATMMachine {
public static void main(String []args) {
// A person can use a machine again, and hence using a "reentrant lock"
Lock machine = new ReentrantLock();
// list of people waiting to access the machine
new Person(machine, "Mickey");
new Person(machine, "Donald");
new Person(machine, "Tom");
new Person(machine, "Jerry");
new Person(machine, "Casper");
}
}