forked from mood321/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSemaphoreDemo.java
More file actions
60 lines (55 loc) · 1.89 KB
/
Copy pathSemaphoreDemo.java
File metadata and controls
60 lines (55 loc) · 1.89 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
package lock.redisson;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.Semaphore;
/**
* @author mood321
* @date 2021/5/3 14:58
* @email [email protected]
*/
public class SemaphoreDemo {
public static void main(String[] args) throws Exception{
final java.util.concurrent.Semaphore semp = new java.util.concurrent.Semaphore(3);
new Thread(new Runnable() {
@Override
public void run() {
try {
System.out.println("线程1 开始执行...");
Thread.sleep(1000);
System.out.println("线程1 执行完毕...");
semp.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}) .start();
new Thread(new Runnable() {
@Override
public void run() {
try {
System.out.println("线程2 开始执行...");
Thread.sleep(1000);
System.out.println("线程2 执行完毕.....");
semp.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}) .start();
new Thread(new Runnable() {
@Override
public void run() {
try {
System.out.println("线程3 开始执行...");
Thread.sleep(1000);
System.out.println("线程3 执行完毕.....");
semp.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}) .start();
System.out.println("主线程 创建子线程完毕..");
semp.acquire(1);
System.out.println("主线程 执行完毕..");
}
}