Create a way
-
Executors.newWorkStealingPool();
- Create a thread pool with preemptive operations
-
Executors.newScheduledThreadPool(10)
- Create a fixed – length thread pool to support scheduled and periodic task execution.
-
Executors.newFixedThreadPool(10)
- Create a fixed-length thread pool that controls the maximum number of concurrent threads, and the excess threads wait in the queue.
-
Executors.newSingleThreadExecutor()
- Thread tasks are executed sequentially, but unlike a single thread, this thread pool only exists for one thread, and when that thread dies, another thread takes over and continues to execute tasks sequentially.
-
Executors.newCachedThreadPool()
- Create a cacheable thread pool. If the length of the thread pool exceeds the processing requirement, you can recycle idle threads flexibly, or create a new thread if none is available. The thread pool is infinite
Seven parameters
- Int corePoolSize: number of core threads
- Int maximumPoolSize: specifies the maximum number of threads
- Long keepAliveTime: indicates the idle time
- TimeUnit unit: TimeUnit
- BlockingQueue workQueue: Block queue
- ThreadFactory ThreadFactory: ThreadFactory class
- RejectedExecutionHandler Handler: Reject the policy
Thread pool processing flow
Rejection policies
The JDK’s built-in rejection policy:
A thread must be created using a thread pool
Do not allow the thread pool to be created by Executors because the maximum number of threads is set to Intege.MAX_VALUE = 21E+. If the thread is created wirelessly, it may cause OOM
Create a thread pool using ThreadPoolExecutor:
# ThreadPoolExecutor
ExecutorService threadPool = new ThreadPoolExecutor(0, 10,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
# Executors
ExecutorService threadPool = Executors.newCachedThreadPool();
Copy the code
Handwritten thread pool
Public static void main(String[] args) {ExecutorService threadPool = new ThreadPoolExecutor(2,// ThreadPoolExecutor 5, New LinkedBlockingDeque<Runnable>(3), // Set the queue size, . The default is an Integer. MAX_VALUE Executors defaultThreadFactory (), / / thread factory new ThreadPoolExecutor CallerRunsPolicy ()); Try {for (int I = 0; i < 10; i++) { threadPool.execute(()->{ System.out.println(Thread.currentThread().getName()); }); } } catch (Exception e){ e.printStackTrace(); } finally { threadPool.shutdown(); }}Copy the code
How to set the maximum number of threads
1. CPU intensive
Number of CPU cores + 1
Runtime.getRuntime().availableProcessors()+1
Copy the code
2. IO intensive
- First: since the IO intensive task thread is not a single task executing, configure as many threads as possible, such as CPU cores x 2
Runtime.getRuntime().availableProcessors() * 2
Copy the code
- The second: