I. Overview
We know that the creation cost of threads is relatively large, so we can also introduce the concept of pools to help realize the concept of resource reuse.
2. Basic use of thread pool
public static void main(String[] args) { // Create a thread pool ExecutorService threadPool = Executors.newCachedThreadPool(); // Add tasks to the thread pool for ( int i = 0 ; i < 10 ; i++ ) { threadPool.execute(() -> { System.out.println(Thread.currentThread().getName()); }); } // Close the thread pool threadPool.shutdown(); }
3. Common thread pools
CacheThreadPool : Buffered thread pool
fixThreadPool : fixed size thread pool
Singleton : A thread pool for a single thread.
4. Summary
Here is just a simple use of the thread pool, and the thread pool will be analyzed in detail later.