Use of thread pool technology
1. Create a thread pool (not used)
ExecutorService threadPool1 = Executors.newFixedThreadPool (3); // fixed size
ExecutorService threadPool2 = Executors.newCachedThreadPool (); // elastically stretchable thread pool, strong, strong case ExecutorService threadPool3 = Executors.newSingleThreadExecutor (); // only one
which There are disadvantages of the thread pool created by this method (Ali's original words)
1) FixedThreadPool and SingleThreadPool: The
allowed request queue length is Integer.MAX_VALUE, which may accumulate a large number of requests, resulting in OOM.
2) CachedThreadPool and ScheduledThreadPool:
The number of allowed creation threads is Integer.MAX_VALUE, which may create a large number of threads, resulting in OOM.
The underlying creation methods are the same:
Executors.newFixedThreadPool(3)底层为:
return new **ThreadPoolExecutor**(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
Executors.newCachedThreadPool()底层为:
return new **ThreadPoolExecutor**(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
Executors.newSingleThreadExecutor()底层为:
new **ThreadPoolExecutor**(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>())
LinkedBlockingQueue does not specify the size, the default is the largest integer.
2. Recommended creation method (recommended)
// Get the current computer or server thread number,
public class ThreadPoolTec {
public static void main(String[] args) {
//推荐的线程池的创建方法
/**
* 最多可以存在的人,maximumPoolSize + LinkedBlockingDeque的容量
*触发非活跃线程变为活跃的方法是:当前任务数量大于最大线程池容量,每超一个则激活一个,直到都被激活
* // 拒绝策略说明:
* // 1. AbortPolicy (默认的:队列满了,就丢弃任务抛出异常!)
* // 2. CallerRunsPolicy(哪来的回哪去? 谁叫你来的,你就去哪里处理)
* // 3. DiscardOldestPolicy (尝试将最早进入对立与的人任务删除,尝试加入队列)
* // 4. DiscardPolicy (队列满了任务也会丢弃,不抛出异常)
*/
Integer processors = Runtime.getRuntime().availableProcessors());
ExecutorService threadPool = new ThreadPoolExecutor(
2,//核心活跃线程数,类比银行两个柜台一直保持营业
processors ,//线程池最大大小,类比银行共5个柜台可以营业
2L,//超时回收空闲的线程,类比有三个非活跃线程处于活跃状态,在一定时间还未接到任务就进入非活跃状态(就是不营业了)
TimeUnit.SECONDS,//时间单位
new LinkedBlockingDeque<>(3),//存放等待任务的队列,类比为银行的候客区,不指定大小的话就是最大整数
Executors.defaultThreadFactory(),// 线程工厂,不修改!用来创建
new ThreadPoolExecutor.CallerRunsPolicy() // 拒绝策略,即候客区满了,不再允许其他人排队了
);
try {
for(int j=1;j<=8;j++){
threadPool.execute(()->{
System.out.println(Thread.currentThread().getName()+"is running………………");
});
}
} catch (Exception e) {
e.printStackTrace();
}finally {
threadPool.shutdown();
}
}
}
Here are a few notes:
1. The maximum number of threads to create a thread pool is the same as the number of threads running the machine is the maximum utilization of resources.
Runtime.getRuntime (). AvailableProcessors ()); is to obtain the maximum number of threads of the current machine
2. The queue of the task queue must specify the size, new LinkedBlockingDeque <> (3), so that there will not be too much waiting.
3. Judgment strategy depends on the specific requirements, I use new ThreadPoolExecutor.CallerRunsPolicy ()
4. Pay attention to the execution of multi-threads, written in lamda:
for (int j = 1; j <= 8; j ++) {
threadPool.execute ( ()-> {
System.out.println (Thread.currentThread (). GetName () + "is running ..................");
});
}
ThreadPoolExecutor underlying working principle:
Rejection strategy flow chart: