出力を理解するのが難しいです。ここで私はエグゼキュータを作成し、Runnable
タスクを1000回送信します。私はRunable
の中にを追加しているので、期待される出力は1000ですが、実際の出力は503ではありません。 BVExecutorService:出力が期待されない
public class FutureTest {
int count=0;
public void testExecutor(){
CountDownLatch counter = new CountDownLatch(1000);
Runnable incr =()->{
//System.out.println("count="+count);
synchronized(this){
count++;
}
counter.countDown();
};
ExecutorService service = Executors.newFixedThreadPool(10);
IntStream.range(0, 1000).forEach(i->service.submit(incr));
counter.await();
service.shutdown();
System.out.println(count);
}
public static void main(String[] args) {
new FutureTest().testExecutor();
}
}
すべてのスレッドが完了する前にカウントを印刷しています。カウントダウンラッチが必要です –
Runnable内に 'Thread.sleep(10)'を追加するだけで意味が分かります。カウントは0 –
@ NathanHughesであり、ここでは 'this'はメインメソッドで作成された' new FutureTest() 'です。 –