一、概述
Semaphore 可以控制某个对象(变量,方法,代码块)的并发访问数量,可用作限流。Semaphore在初始化时可以指定多少个许可证。如果需要访问某个被Semaphore控制的对象,线程只有在获取到许可证的情况下才能访问,否则就一直阻塞直到获取到许可证或者线程被中断。Semaphore可以设置公平策略和非公平策略,当设置为false时,Semaphore不会保证线程获取许可证的顺序。
二、构造方法
public Semaphore(int permits):permits 初始化state的值,指定许可数量,默认非公平策略
public Semaphore(int permits, boolean fair):permits 初始化state的值,指定许可数量,fair可指定公平策略或非公平策略。
三、主要方法
public void acquire() throws InterruptedException:从这个Semaphore中获取一个许可证,如果没有可用许可则阻塞,直到有一个可用许可或调用线程中断。调用线程中断时抛出InterruptedException异常。
public void acquire(int permits) throws InterruptedException:从这个Semaphore中获取permits个许可证。否则阻塞直到这些个许可可用或调用线程被中断。线程被中断抛出InterruptedException异常,permits小于零抛出IllegalArgumentException异常。
public void release():释放一个许可证,返回给Semaphore对象,可用许可证的数量加一。
public int availablePermits():返回当前可用的许可数量。
public boolean tryAcquire():???仅当调用时有一个许可证可用的情况,才能从这个Semaphore中获取这个可用的许可证。成功获取返回true,否则返回false ???
四、代码
package com.scott.current;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
public class SemaphoreDemo2 {
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
final Semaphore semaphore = new Semaphore(2);
for (int index = 0; index < 5; index++) {
final int NO = index;
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
semaphore.acquire();
// semaphore.tryAcquire();
System.out.println(Thread.currentThread().getName() + "\t" + "Accessing:" + NO + "\t" + "时间:" + System.currentTimeMillis());
Thread.sleep((long) (Math.random() * 10000));
semaphore.release();
System.out.println(Thread.currentThread().getName() + "------------------" + semaphore.availablePermits() + "\t" + "时间:" + System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
executorService.execute(runnable);
System.out.println(Thread.currentThread().getName() + "第" + (index + 1) + "次循环");
}
executorService.shutdown();
}
}
执行结果:
由执行结果可以看出,后面的都是释放一个许可证两外一个线程才能获得一个可用的许可证。算了,遍不下去了。