Card 02/ 09

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.

java
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();
text
pool-1-thread-1 0
pool-1-thread-4 3
pool-1-thread-4 5
pool-1-thread-4 6
pool-1-thread-4 7
the first five lines of one run

Four 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.