題目

代碼實作:
寫法一:
class Foo {
public Foo() {
}
volatile int count = 1;
public void first(Runnable printFirst) throws InterruptedException {
count++;
// printFirst.run() outputs "first". Do not change or remove this line.
printFirst.run();
}
public void second(Runnable printSecond) throws InterruptedException {
while(count != 2);
// printSecond.run() outputs "second". Do not change or remove this line.
printSecond.run();
count++;
}
public void third(Runnable printThird) throws InterruptedException {
while(count != 3);
// printThird.run() outputs "third". Do not change or remove this line.
printThird.run();
}
}

寫法二:
class Foo {
private Semaphore two = new Semaphore(0);//這里設定為0,就是一開始使執行緒阻塞從而完成其他執行,也是可以進行release和acquire操作(此處為這種解釋)
private Semaphore three = new Semaphore(0);
public Foo() {
}
public void first(Runnable printFirst) throws InterruptedException {
// printFirst.run() outputs "first". Do not change or remove this line.
printFirst.run();
two.release();
}
public void second(Runnable printSecond) throws InterruptedException {
two.acquire();
// printSecond.run() outputs "second". Do not change or remove this line.
printSecond.run();
three.release();
}
public void third(Runnable printThird) throws InterruptedException {
three.acquire();
// printThird.run() outputs "third". Do not change or remove this line.
printThird.run();
}
}

信號量的原理
信號量維護了一個信號量許可集,執行緒可以通過呼叫 acquire() 來獲取信號量的許可;當信號量中有可用的許可時,執行緒能獲取該許可;否則執行緒必須等待,直到有可用的許可為止, 執行緒可以通過 release() 來釋放它所持有的信號量許可,
Semaphore 的函式串列
// 創建具有給定的許可數和非公平的公平設定的 Semaphore,
Semaphore(int permits)
// 創建具有給定的許可數和給定的公平設定的 Semaphore,
Semaphore(int permits, boolean fair)
// 從此信號量獲取一個許可,在提供一個許可前一直將執行緒阻塞,否則執行緒被中斷,
void acquire()
// 從此信號量獲取給定數目的許可,在提供這些許可前一直將執行緒阻塞,或者執行緒已被中斷,
void acquire(int permits)
// 從此信號量中獲取許可,在有可用的許可前將其阻塞,
void acquireUninterruptibly()
// 從此信號量獲取給定數目的許可,在提供這些許可前一直將執行緒阻塞,
void acquireUninterruptibly(int permits)
// 回傳此信號量中當前可用的許可數,
int availablePermits()
// 獲取并回傳立即可用的所有許可,
int drainPermits()
// 回傳一個 collection,包含可能等待獲取的執行緒,
protected Collection<Thread> getQueuedThreads()
// 回傳正在等待獲取的執行緒的估計數目,
int getQueueLength()
// 查詢是否有執行緒正在等待獲取,
boolean hasQueuedThreads()
// 如果此信號量的公平設定為 true,則回傳 true,
boolean isFair()
// 根據指定的縮減量減小可用許可的數目,
protected void reducePermits(int reduction)
// 釋放一個許可,將其回傳給信號量,
void release()
// 釋放給定數目的許可,將其回傳到信號量,
void release(int permits)
// 回傳標識此信號量的字串,以及信號量的狀態,
String toString()
// 僅在呼叫時此信號量存在一個可用許可,才從信號量獲取許可,
boolean tryAcquire()
// 僅在呼叫時此信號量中有給定數目的許可時,才從此信號量中獲取這些許可,
boolean tryAcquire(int permits)
// 如果在給定的等待時間內此信號量有可用的所有許可,并且當前執行緒未被中斷,則從此信號量獲取給定數目的許可,
boolean tryAcquire(int permits, long timeout, TimeUnit unit)
// 如果在給定的等待時間內,此信號量有可用的許可并且當前執行緒未被中斷,則從此信號量獲取一個許可,
boolean tryAcquire(long timeout, TimeUnit unit)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/260396.html
標籤:java
下一篇:Java基礎-final關鍵字
