Card 02/ 09
All 9 cards
ExampleDifficulty: Intermediate1 min
Ten Thousand Short Tasks Through Four Threads
The same work submitted two ways, with the thread name printed so you can see how many there really are.
ExecutorService pool = Executors.newFixedThreadPool(4);
for (int i = 0; i < 10_000; i++) {
int n = i;
pool.submit(() -> System.out.println(Thread.currentThread().getName() + " " + n));
}
pool.shutdown();pool-1-thread-1 0
pool-1-thread-4 3
pool-1-thread-4 5
pool-1-thread-4 6
pool-1-thread-4 7Four threads, ten thousand tasks. pool-1-thread-4 takes four of the first five, because it finished each one and came straight back for another — which is exactly what a thread that outlives its work is for.
Task 3 came out before tasks 1 and 2, and nothing promised otherwise. Submitting is not running — it puts the task on a queue, and the pool decides which thread takes it and when.