Semaphore

这是一个同步工具类,可以维护当前访问自身的线程个数

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
public class SemaphoreDemo {
public static void main(String[] args) {
//允许两个个线程同时执行
Semaphore s = new Semaphore(2);
//允许两个个线程同时执行,先入先出
//Semaphore s = new Semaphore(2, true);
//允许一个线程同时执行
//Semaphore s = new Semaphore(1);

new Thread(()->{
try {
s.acquire(); //获取许可
System.out.println("T1 running...");
System.out.println(s.availablePermits()); //返回可用许可数
Thread.sleep(2000);
System.out.println("T1 end...");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
s.release(); //释放许可
}
}).start();

new Thread(()->{
try {
s.acquire();
System.out.println("T2 running...");
Thread.sleep(2000);
System.out.println(s.hasQueuedThreads()); //查询是否有线程正在等待获取
System.out.println("T2 end...");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
s.release();
}
}).start();

new Thread(()->{
try {
s.acquire();
System.out.println("T3 running...");
Thread.sleep(2000);
System.out.println("T3 end...");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
s.release();
}
}).start();
}
}

acquire() 获取许可

release() 释放许可

availablePermits() 返回信号量里可以用的许可数

hasQueuedThreads() 查询是否有正在等待的获取