-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathConnectionLimiter.java
70 lines (53 loc) · 1.89 KB
/
ConnectionLimiter.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
package semaphore;
import java.util.concurrent.Semaphore;
/**
* This is a small program to demo how semaphore can create trouble for us.
* One rule of thumb is:
* Always release what you acquire!
* Copied from the Internet.
*/
//this is a bad public class name, it doesn't apply to
//what this class really do, it's a name from a different class that I copied earlier.
public class ConnectionLimiter {
private static class DoubleResourceGrabber implements Runnable {
private Semaphore first;
private Semaphore second;
public DoubleResourceGrabber(Semaphore s1, Semaphore s2) {
first = s1;
second = s2;
}
@Override
public void run() {
Thread t = Thread.currentThread();
try {
first.acquire();
System.out.println(t.getName() + " acquired " + first);
// Thread.sleep(20);//to demo a deadlock
// second.acquire();
// System.out.println(t.getName() + " acquired " + second);
// second.release();
// System.out.println(t.getName() + " released " + second);
first.release();
System.out.println(t.getName() + " released " + first);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
Semaphore s1 = new Semaphore(1);//give it only 1 permit
Semaphore s2 = new Semaphore(1);//give it only 1 permit as well
Thread t1 = new Thread(new DoubleResourceGrabber(s1, s2));
//now reverse them, here comes the trouble
Thread t2 = new Thread(new DoubleResourceGrabber(s2, s1));
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("We got lucky!");
}
}