forked from lihengming/java-codes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSemaphoreTest.java
More file actions
51 lines (46 loc) · 1.44 KB
/
Copy pathSemaphoreTest.java
File metadata and controls
51 lines (46 loc) · 1.44 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
package juc;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
/**
* Created by 李恒名 on 2017/6/18.
*/
public class SemaphoreTest {
public static void main(String[] args) {
WC wc = new WC();
new Thread(() -> wc.use()).start();
new Thread(() -> wc.use()).start();
new Thread(() -> wc.use()).start();
new Thread(() -> wc.use()).start();
new Thread(() -> wc.use()).start();
/**
输出:
Thread-1 正在使用卫生间
Thread-2 正在使用卫生间
Thread-0 正在使用卫生间
Thread-0 使用完毕
Thread-2 使用完毕
Thread-1 使用完毕
Thread-3 正在使用卫生间
Thread-4 正在使用卫生间
Thread-4 使用完毕
Thread-3 使用完毕
*/
}
}
class WC {
private Semaphore semaphore = new Semaphore(3);//最大线程许可量
public void use() {
try {
//获得许可
semaphore.acquire();
System.out.println(Thread.currentThread().getName() +" 正在使用卫生间");
TimeUnit.SECONDS.sleep(3);
System.out.println(Thread.currentThread().getName() +" 使用完毕");
} catch (InterruptedException e) {
e.printStackTrace();
} finally{
//释放许可
semaphore.release();
}
}
}