LinkedBlockingQueueのマルチスレッドでの挙動について
以下のコードでなぜ出力結果の6行目がoffer():3になるのでしょうか?
java
1 BlockingQueue<Double> queue = new LinkedBlockingQueue<>(3); 2 new Thread(() -> { 3 while(true){ 4 try { 5 queue.offer(Math.random(), 2, TimeUnit.SECONDS); 6 System.out.println("offer() : " + queue.size()); 7 } catch (InterruptedException e) { e.printStackTrace(); } 8 } 9 }).start(); 10 11 new Thread(() -> { 12 while(true){ 13 try { 14 double pNum = queue.poll(2, TimeUnit.SECONDS); 15 System.out.println("poll() : " + pNum); 16 } catch (InterruptedException e) { e.printStackTrace(); } 17 } 18 }).start();
offer():1
offer():2
offer():3
poll():0.24829714919143642
poll():0.9951008257323133
offer():3 ⇦なんで要素が3個?? 上2行で二つ削除されてるからここは2と表示されるのでは?
poll():0.2502551360660312
poll():0.931467810599396
poll():0.08339082618949567
offer():2
以降続く...
いろんなパターンを考えてみましたが、どう頑張っても6行目が3になるパターンが分りません。
どのようなときに3になるのでしょうか?
回答1件
あなたの回答
tips
プレビュー