要件:無制限のブロッキングキューを実装します。制限のないブロッキングキューJava
public class BlockingQueue<T> {
private Queue<T> queue = new LinkedList<>();
private Object monitor = new Object();
/**
* add element to queue
*/
public void add(T element) {
synchronized (monitor) {
queue.add(element);
monitor.notify();
}
}
/**
* Returns element if present in queue
* otherwise calling thread blocks until an element is added to queue
*
* @return element from queue
*/
public T get() throws InterruptedException {
synchronized (monitor) {
while (queue.isEmpty()) {
monitor.wait();
}
return queue.poll();
}
}
}
質問
1.正しい実装ですか?
2. wait()を呼び出します。スレッドをRUNNABLEからWAIT状態に移動します。
notify()を呼び出します。スレッドをWAITからBLOCKED状態にする
スレッドがBLOCKED状態からRUNNABLE状態に移動するアクションはありますか?
1.明らかに、はい。しかし、それをテストする必要があります。 2. BLOCKEDは、モニター・ロックを待機しているスレッドのブロック状態です。このようにして、モニタが解放されたとき、すなわちモニタを所有するスレッドがその同期ブロックから抜け出るときに、BLOCKEDからRUNNINGに進む。 –
両方の質問にはいります。 – SMA
ArrayBlockingQueueソースコードを確認してください:http://grepcode.com/file_/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/concurrent/ArrayBlockingQueue.java/?v=source –