1. Semaphore 是什么?
Semaphore 字面意思是信號量的意思,它的作用是控制訪問特定資源的線程數目。
2. 怎么使用 Semaphore?
2.1 構造方法
public Semaphore(int permits) public Semaphore(int permits, boolean fair)
解析:
- permits 表示許可線程的數量
- fair 表示公平性,如果這個設為 true 的話,下次執行的線程會是等待最久的線程
2.2 重要方法
public void acquire() throws InterruptedException public void release()
解析:
- acquire() 表示阻塞並獲取許可
- release() 表示釋放許可
2.3 基本使用
2.3.1 需求
多個線程同時執行,但是限制同時執行的線程數量為 2 個。
2.3.2 代碼實現
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(); } } }
打印結果:
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()。
需要注意的是 Semaphore 只是對資源並發訪問的線程數進行監控,並不會保證線程安全。
3. Semaphore 使用場景
可用於流量控制,限制最大的並發訪問數。
https://mp.weixin.qq.com/s/8m_RhTyVftgc5UX6ABX2vA