Semaphore 字面意思是信号量的意思,它的做用是控制访问特定资源的线程数目。安全
public Semaphore(int permits) public Semaphore(int permits, boolean fair)
解析:并发
public void acquire() throws InterruptedException public void release()
解析:ide
多个线程同时执行,可是限制同时执行的线程数量为 2 个。ui
public class SemaphoreDemo { static class TaskThread extends Thread { Semaphore semaphore; public TaskThread(Semaphore semaphore) { this.semaphore = semaphore; } @Override public void run() { try { semaphore.acquire(); System.out.println(getName() + " acquire"); Thread.sleep(1000); semaphore.release(); System.out.println(getName() + " release "); } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String[] args) { int threadNum = 5; Semaphore semaphore = new Semaphore(2); for (int i = 0; i < threadNum; i++) { new TaskThread(semaphore).start(); } } }
打印结果:this
Thread-1 acquire Thread-0 acquire Thread-0 release Thread-1 release Thread-2 acquire Thread-3 acquire Thread-2 release Thread-4 acquire Thread-3 release Thread-4 release
从打印结果能够看出,一次只有两个线程执行 acquire(),只有线程进行 release() 方法后才会有别的线程执行 acquire()。spa
须要注意的是 Semaphore 只是对资源并发访问的线程数进行监控,并不会保证线程安全。线程
可用于流量控制,限制最大的并发访问数。code
https://mp.weixin.qq.com/s/8m_RhTyVftgc5UX6ABX2vAblog