Semaphore
它就是我们之前在讲源码的时候提到的 信号量 ,下面看下它的构造函数。
public Semaphore(int permits) { sync = new NonfairSync(permits); } public Semaphore(int permits, boolean fair) { sync = fair ? new FairSync(permits) : new NonfairSync(permits); }
从构造函数可以看出,它可以传入指定数量的资源和指定公平和非公平锁,公平和非公平就不多阐述了。
我们重点关注的是acquire()和release(), 这两个方法字面意思很好理解, Semaphore往往用于资源有限的场景,比如我们需要限制某个操作的线程数量。下面通过例子感受一下。
public class SemaphoreTest { public static final class Task implements Runnable { private int num; private Semaphore semaphore; public Task(int num, Semaphore semaphore) { this.num = num; this.semaphore = semaphore; } @Override public void run() { try { // 获取 semaphore.acquire(); System.out.println(String.format("num: %d, 剩余%d个资源, 还有%d个线程在等待", num, semaphore.availablePermits(), semaphore.getQueueLength())); System.out.println(System.currentTimeMillis()); Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } finally { // 释放 System.out.println("释放资源"); semaphore.release(); } } } public static void main(String[] args) { Semaphore semaphore = new Semaphore(2); IntStream.range(0, 20).forEach(i -> new Thread(new Task(i, semaphore)).start()); } }
实际输出:
num: 1, 剩余0个资源, 还有0个线程在等