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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
|
import
java.util.*;
import
java.util.concurrent.ExecutorService;
import
java.util.concurrent.Executors;
import
java.util.concurrent.Semaphore;
import
java.util.concurrent.locks.ReentrantLock;
/**
* 信號量使用詳解,使用信號量來管理有限的資源
* User: ketqi
* Date: 2013-01-27 12:29
*/
public
class
SemaphoreDemo {
/** 可重入鎖,對資源列表進行同步 */
private
final
ReentrantLock lock =
new
ReentrantLock();
/** 信號量 */
private
final
Semaphore semaphore;
/** 可以使用的資源列表 */
private
final
LinkedList<Object> resourceList =
new
LinkedList<Object>();
public
SemaphoreDemo(Collection<Object> resourceList) {
this
.resourceList.addAll(resourceList);
this
.semaphore =
new
Semaphore(resourceList.size(),
true
);
}
/**
* 獲取資源
*
* @return 可用的資源
* @throws InterruptedException
*/
public
Object acquire()
throws
InterruptedException {
semaphore.acquire();
lock.lock();
try
{
return
resourceList.pollFirst();
}
finally
{
lock.unlock();
}
}
/**
* 釋放或者歸還資源
*
* @param resource 待釋放或歸還的資源
*/
public
void
release(Object resource) {
lock.lock();
try
{
resourceList.addLast(resource);
}
finally
{
lock.unlock();
}
semaphore.release();
}
public
static
void
main(String[] args) {
//準備2個可用資源
List<Object> resourceList =
new
ArrayList<>();
resourceList.add(
"Resource1"
);
resourceList.add(
"Resource2"
);
//準備工做任務
final
SemaphoreDemo demo =
new
SemaphoreDemo(resourceList);
Runnable worker =
new
Runnable() {
@Override
public
void
run() {
Object resource =
null
;
try
{
//獲取資源
resource = demo.acquire();
System.out.println(Thread.currentThread().getName() +
"\twork on\t"
+ resource);
//用resource作工做
Thread.sleep(
1000
);
System.out.println(Thread.currentThread().getName() +
"\tfinish on\t"
+ resource);
}
catch
(InterruptedException e) {
e.printStackTrace();
}
finally
{
//歸還資源
if
(resource !=
null
) {
demo.release(resource);
}
}
}
};
//啓動9個任務
ExecutorService service = Executors.newCachedThreadPool();
for
(
int
i =
0
; i <
9
; i++) {
service.submit(worker);
}
service.shutdown();
}
}
|