Java 多執行緒高併發 3.3 — Semaphore 共享鎖使用
阿新 • • 發佈:2018-12-11
- Semaphore 是共享鎖的一種,字面上意思就是訊號量鎖
- 顧名思義,一個可以共享的鎖,可以讓多個執行緒共享同一把鎖,例如同一條馬路可以讓 4 臺車同時並行跑,相當於可以讓 4 個執行緒共享一把鎖,臨界區的限制也就是 4
- 會有一個臨界區,用於控制執行緒,只有拿到訊號量(許可)才能的進入
- 一個執行緒可以拿多個許可,但是一般情況不會這樣做,還是看業務需求咯~~
- 常常用在併發控制的場景
主要 api
名稱 | 用法 |
---|---|
acquire() | 獲取一個訊號量(許可) |
acquire(int permits) | 獲取 permits 數量的訊號量,在獲取到 permits 數量的訊號量之前會一直阻塞等待,並且數量必須小於等於 Semaphore 允許的總訊號量,否則會出現死鎖 |
acquireUninterruptibly() | 獲取一個不可被中斷的訊號量 |
tryAcquire() | 嘗試去回去一個訊號量,獲取到了,返回 true,否則 false |
tryAcquire(long timeout, TimeUnit unit) | 在限定時間內嘗試去回去一個訊號量,獲取到了,返回 true,否則 false |
release() | 釋放當前的訊號量 |
release(int permits) | 同樣,上面獲取了多少個訊號量,這裡就需要釋放多少個,否則容易出現死鎖一直等待的情況 |
簡要使用
public class TestSemaphore {
// 限定執行緒數量
private static final Semaphore semaphore = new Semaphore(3);
static class TestThread implements Runnable {
@Override
public void run() {
try {
semaphore.acquire(2);
System.out.println(System.currentTimeMillis() + " :" + Thread.currentThread().getName() + " 進來了");
Thread.sleep (3000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release(2);
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new TestThread(), "Thread TestThread1");
Thread t2 = new Thread(new TestThread(), "Thread TestThread2");
Thread t3 = new Thread(new TestThread(), "Thread TestThread3");
Thread t4 = new Thread(new TestThread(), "Thread TestThread4");
t1.start();
t2.start();
t3.start();
t4.start();
}
}
輸出 1537843926834 :Thread TestThread1 進來了 1537843929834 :Thread TestThread3 進來了 1537843932835 :Thread TestThread2 進來了 1537843935835 :Thread TestThread4 進來了