-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSynchronizedTest.java
More file actions
64 lines (56 loc) · 1.52 KB
/
SynchronizedTest.java
File metadata and controls
64 lines (56 loc) · 1.52 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
63
64
/**
* Created by zhuliting on 17-4-1.
*/
class Reservoir {
private int total;
public Reservoir(int total) {
this.total = total;
}
public synchronized boolean sellTicket() {
if (this.total > 0) {
this.total = this.total - 1;
return true;
}
else {
return false;
}
}
}
class Booth extends Thread {
private static int threadID = 0;
private Reservoir release;
private int count = 0;
public Booth(Reservoir release) {
super("id: " + (++threadID));
this.release = release;
this.start();
}
public String toString() {
return super.getName();
}
public void run() {
while (true) {
if (this.release.sellTicket()) {
this.count = this.count + 1;
// System.out.println(this.getName() + ": sell 1");
try {
sleep((int)(Math.random()*10));
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
// System.out.println("not enough ticket!");
break;
}
}
System.out.println(this.getName() + ": I sold " + this.count);
}
}
public class SynchronizedTest {
public static void main(String[] args) {
Reservoir reservoir = new Reservoir(100);
Booth b1 = new Booth(reservoir);
Booth b2 = new Booth(reservoir);
Booth b3 = new Booth(reservoir);
}
}