Java – ThreadPoolExecutor: how does it reuse threads
I read about ThreadPoolExecutor wired process pool, which is destined to reduce the cost of creating new threads (at least I understand the following phrase in this way):
However, as far as I know, we can't restart threads in Java
Question: how does ThreadPoolExecutor avoid creating new threads?
Solution
It's very simple - essentially threads sleep, waiting to be awakened by a task - they run the task and then sleep again
public static void main(final String[] args) throws Exception { final BlockingQueue<Runnable> blockingQueue = new LinkedBlockingDeque<>(); final Thread t = new Thread(new Runnable() { @Override public void run() { while (true) { try { blockingQueue.take().run(); } catch (InterruptedException ex) { return; } } } }); t.start(); blockingQueue.add(new Runnable() { @Override public void run() { System.out.println("Task 1"); } }); blockingQueue.add(new Runnable() { @Override public void run() { System.out.println("Task 2"); } }); }
BlockingQueue blocks it when it is empty When I add a project, the currently blocked thread will wake up and execute the task (linked blocking deque is thread safe) When a thread completes its task, it will go back to sleep
The Javadoc of ThreadPoolExecutor describes the logic in detail All constructors of ThreadPoolExecutor use BlockingQueue < runnable > – this should give you a hint because of how logic works
Note: This is different from busy waiting Blocking queue uses wait and notify to suspend and wake up threads, which means that threads in the pool do not do any work when they are not processing tasks The busy wait based approach does not work because the thread will block all CPU cores and its polling does not allow the program to continue (or at least seriously damage it)