Card 02/ 09

ExampleDifficulty: Intermediate1 min

Thread Pool Example: Ten Thousand Tasks Through Four Threads

The thread names show four threads doing all the work, and tasks finishing out of order.

Submitting ten thousand tasks to a pool of four threads, and printing the name of the thread that runs each one, shows the pool reusing its threads and deciding the order itself.

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