Executors and thread pools · Topic 2 of 7
Fixed thread pool
Definition​
An executor runs tasks for you on a pool of reusable threads. A fixed thread pool has a set number of threads: extra tasks wait in a queue until a thread is free. You submit work and the pool handles the threads.
Example code​
Ten tasks on three threads
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
class Demo {
public static void main(String[] args) throws InterruptedException {
ExecutorService pool = Executors.newFixedThreadPool(3);
Set<String> threadsUsed = ConcurrentHashMap.newKeySet();
for (int i = 0; i < 10; i++) {
pool.submit(() -> threadsUsed.add(Thread.currentThread().getName()));
}
pool.shutdown();
pool.awaitTermination(5, TimeUnit.SECONDS);
System.out.println("10 tasks ran on at most 3 threads: " + (threadsUsed.size() <= 3));
}
}
// Output:
// 10 tasks ran on at most 3 threads: true
Finished this page? Track your progress (saved only in your browser).