java并发编程之semaphore

信号量是对锁的扩展,无论是synchronized还是ReetrantLock,一次都只允许一个线程访问一个资源,而信号量却可以指定多个线程,同时访问一个资源。

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
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class implements Runnable {
final Semaphore semp = new Semaphore(5);

public static void main(String[] args) throws Exception {
ExecutorService exec = Executors.newFixedThreadPool(20);
final Shit shit = new Shit();
for (int i = 0; i < 20; i++) {
exec.submit(shit);
}
}


public void run() {
try {
semp.acquire();
Thread.sleep(2000);
System.out.println(Thread.currentThread().getId() + ":done");
semp.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

上面这个例子中,将会输出以5个线程为一组的提示文本。