[Java] Semaphore的使用時機

Java所提供的SemaphoreOperating System Concepts上所講的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
import java.util.concurrent.Semaphore;

public class SemaphoreDemo {

Semaphore pool = new Semaphore(10);

public static void main(String args[]) {
final SemaphoreDemo demo = new SemaphoreDemo();

for (int i = 0; i < 30; i++) {
new Thread(new Runnable() {

@Override
public void run() {
demo.mutualExclusion();
}

}, "Thread" + i).start();

}
}

private void mutualExclusion() {
try {
pool.acquire();

System.out.println(Thread.currentThread().getName() + " inside mutual exclusive region");
Thread.sleep(1000);

}
catch (InterruptedException e) {
e.printStackTrace();
}
finally {
pool.release();
System.out.println(Thread.currentThread().getName() + " outside of mutual exclusive region");
}
}

}

當pool為空的時候,想要使用pool資源的thread會進入blocking狀態,直到有其他thread執行release()釋放pool資源,喚醒其中在blocking狀態的thread。

參考資料:

Counting Semaphore Example in Java 5 – Concurrency Tutorial