1、Semaphore概念
Semaphore是Java1.5之后提供的一种同步工具,Semaphore可以维护访问自身线程个数,并提供了同步机制。使用Semaphore可以控制同时访问资源的线程个数,通过 acquire() 获取一个许可,如果没有就等待,而release() 释放一个许可。
Semaphore实现的功能就类似厕所有5个坑,假如有10个人要上厕所,那么同时只能有多少个人去上厕所呢?同时只能有5个人能够占用,当5个人中 的任何一个人让开后,其中等待的另外5个人中又有一个人可以去占用了。另外等待的5个人中可以是随机获得优先机会,也可以是按照先来后到的顺序获得机会,这取决于构造Semaphore对象时传入的参数选项。单个信号量的Semaphore对象可以实现互斥锁的功能,并且可以是由一个线程获得了“锁”,再由另一个线程释放“锁”,这可应用于死锁恢复的一些场合,所以单个信号量的Semaphore对象的功能就和synchronized实现互斥是共同的
2、功能扩展
3、Semaphore的使用demo如下
-
public class SemahoreDemo {
-
-
public static void main(String[] args) {
-
ExecutorService executorService = Executors.newCachedThreadPool();
-
-
final Semaphore semaphore = new Semaphore(1,true);
-
-
for(int i=0;i<10;i++){
-
Runnable runnable = new Runnable() {
-
-
public void run() {
-
try {
-
semaphore.acquire();
-
} catch (InterruptedException e) {
-
e.printStackTrace();
-
}
-
-
System.err.println("线程"+Thread.currentThread().getName()+"进入,已有"+(3-semaphore.availablePermits())+"并发");
-
-
try {
-
Thread.sleep((long)(Math.random()*1000));
-
} catch (InterruptedException e) {
-
e.printStackTrace();
-
}
-
-
System.out.println("线程"+Thread.currentThread().getName()+"即将离开");
-
-
semaphore.release();
-
-
System.err.println("线程"+Thread.currentThread().getName()+"已经离开"+"当前并发数:"+(3-semaphore.availablePermits()));
-
}
-
};
-
-
executorService.execute(runnable);
-
}
-
-
executorService.shutdown();
-
-
}
-
-
}