Skip to content

Commit 7176a28

Browse files
committed
Semaphore
1 parent 5a7d6db commit 7176a28

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

src/chapter3/SemapDemo.java

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package chapter3;
2+
3+
import java.util.concurrent.ExecutorService;
4+
import java.util.concurrent.Executors;
5+
import java.util.concurrent.Semaphore;
6+
7+
/**
8+
* 信号量
9+
* Created by 13 on 2017/5/5.
10+
*/
11+
public class SemapDemo implements Runnable {
12+
final Semaphore semp = new Semaphore(5);
13+
14+
@Override
15+
public void run() {
16+
try {
17+
semp.acquire();
18+
Thread.sleep(2000);
19+
System.out.println(Thread.currentThread().getId() + ":done!");
20+
semp.release();
21+
} catch (InterruptedException e) {
22+
e.printStackTrace();
23+
}
24+
}
25+
26+
/**
27+
* 总共20个线程,系统会以5个线程一组为单位,依次执行并输出
28+
*
29+
* @param args
30+
*/
31+
public static void main(String args[]) {
32+
ExecutorService executorService = Executors.newFixedThreadPool(20);
33+
final SemapDemo demo = new SemapDemo();
34+
for (int i = 0; i < 20; i++) {
35+
executorService.submit(demo);
36+
}
37+
}
38+
}

0 commit comments

Comments
 (0)