###分からないこと
現在、教材でThreadの勉強をしています。LinkedBlockingQueueクラスを利用したサンプルコードがあるのですが、実行結果がなぜそうなるのかわかりません。
3つofferで要素を追加 → 3つpollで要素を削除
これの繰り返しにならないのでしょうか?
また、実行結果の4,5行目でpollで要素を2つ削除しているのに6行目でofferのあと、要素数が3になっているのも謎です。
###ソースコード
import java.util.concurrent.*;
public class Sample10_9 {
public static void main(String[] args) {
BlockingQueue<Double> queue = new LinkedBlockingQueue<>(3);
new Thread(() -> { //キューに要素を追加するスレッド
while(true) {
try {
queue.offer(Math.random(), 2, TimeUnit.SECONDS);
System.out.println("offer() : " + queue.size());
} catch (InterruptedException e) { e.printStackTrace(); }
}
}).start();
new Thread(() -> { //キューから要素を取得および削除するスレッド while(true) { try { double pNum = queue.poll(2, TimeUnit.SECONDS); System.out.println("poll() : " + pNum); } catch (InterruptedException e) { e.printStackTrace(); } } }).start();
}
}
###実行結果
offer(): 1
offer(): 2
offer(): 3
poll(): 0.24829714919143642
poll(): 0.9951008257327133
offer(): 3
poll(): 0.2502551360660312
poll(): 0.931467810599396
poll(): 0.08339082618949567
offer(): 2
<続く>
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/03/16 06:54
2017/03/16 07:13
2017/03/16 07:45
2017/03/16 08:37
2017/03/16 09:45
2017/03/26 07:19
2017/03/26 15:38
2017/03/26 15:56