文章目錄
-
-
- 1. Semaphore 是什麼?
- 2. 怎麼使用 Semaphore?
-
- 2.1 構造方法
- 2.2 重要方法
- 2.3 基本使用
-
- 2.3.1 需求場景
- 2.3.2 代碼實作
- 相關學習路線
-
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()
tryAcquire(long timeout, TimeUnit unit)
acquire() 表示阻塞并擷取許可
release() 表示釋放許可
2.3 基本使用
2.3.1 需求場景
資源通路,服務限流。
2.3.2 代碼實作
import java.util.concurrent.Semaphore;
/**
* @description :可用于流量控制,限制最大的并發通路數
*/
public class SemaphoreSample {
public static void main(String[] args) {
Semaphore semaphore = new Semaphore(2);
for (int i=0;i<5;i++){
new Thread(new Task(semaphore,"silas+"+i)).start();
}
}
static class Task extends Thread{
Semaphore semaphore;
public Task(Semaphore semaphore,String tname){
this.semaphore = semaphore;
this.setName(tname);
}
public void run() {
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName()+":acquire() at time:"+System.currentTimeMillis());
Thread.sleep(2000);
semaphore.release();
System.out.println(Thread.currentThread().getName()+":release() at time:"+System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
列印結果:
Thread-1:acquire() at time:1571208530724
Thread-3:acquire() at time:1571208530727
Thread-1:release() at time:1571208532725
Thread-5:acquire() at time:1571208532725
Thread-3:release() at time:1571208532727
Thread-7:acquire() at time:1571208532727
Thread-5:release() at time:1571208534726
Thread-9:acquire() at time:1571208534726
Thread-7:release() at time:1571208534728
Thread-9:release() at time:1571208536727
Process finished with exit code 0
從列印結果可以看出,一次隻有兩個線程執行 acquire(),隻有線程進行 release() 方法後 才會有别的線程執行 acquire()。
相關學習路線
JAVA資深架構師成長路線->架構師築基必備技能->并發程式設計進階