Home >Java >javaTutorial >What are the four thread pools that come with Java?
newSingleThreadExexcutor: Thread pool with a single number of threads (number of core threads = maximum number of threads = 1)
newFixedThreadPool: Fixed number of threads Pool (number of core threads = maximum number of threads = custom)
newCacheThreadPool: Cacheable thread pool (number of core threads = 0, maximum number of threads = Integer.MAX_VALUE)
newScheduledThreadPool: Thread pool that supports scheduled or periodic tasks (number of core threads = custom, maximum number of threads = Integer.MAX_VALUE)
The above four thread pool classes all inherit ThreadPoolExecutor and directly return new ThreadPoolExecutor (parameters) when created. The difference between them is that the parameters in the defined ThreadPoolExecutor (parameters) are different, and ThreadPoolExecutor inherits the ExecutorService interface class.
newFixedThreadPool
Definition:
xecutorService executorService=Executors.newFixedThreadPool(2);
Disadvantages: LinkBlockQueue's linked list blocking queue is used. When the accumulation speed of tasks is greater than the processing speed, it is easy to accumulate tasks and cause OOM memory overflow
newSingleThreadExecutor
##Definition: ExecutorService executorService =Executors.newSingleThreadExecutor();The above code is similar new FixedThreadPoop(1), but there is a difference, because there is an extra layer of FinalizableDelegatedExecutorService, its function: It can be seen that the essence of fixedExecutorService is ThreadPoolExecutor, so fixedExecutorService can be forced to transfer into ThreadPoolExecutor, but singleExecutorService has nothing to do with ThreadPoolExecutor, so the forced transfer fails. Therefore, after newSingleThreadExecutor() is created, its thread pool parameters cannot be modified, and it is truly a single thread. Disadvantages: LinkBlockQueue's linked list blocking queue is used. When the accumulation speed of tasks is greater than the processing speed, it is easy to accumulate tasks and cause OOM memory overflownewCacheThreadPool
Definition: ExecutorService executorService=Executors.newCacheThreadPool();Disadvantages: SynchronousQueue is an implementation of BlockingQueue, it is also a queue, because the maximum number of threads is Integer.MAX_VALUE, so when there are too many threads, it is easy to OOM memory overflowScheduledThreadPool
Definition: ExecutorService executorService=Executors.newScheduledThreadPool(2);What are the important parameters of the thread pool? ThreadPoolExecutor construction method is as follows:源码: public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) { //ScheduledThreadPoolExecutor继承ThreadPoolExecutor return new ScheduledThreadPoolExecutor(corePoolSize); } public ScheduledThreadPoolExecutor(int corePoolSize) { //ScheduledThreadPoolExecutor继承ThreadPoolExecutor,故super()会调用ThreadPoolExecutor的构造函数初始化并返回一个ThreadPoolExecutor,而ThreadPoolExecutor使实现ExecutorService接口的 //最终ScheduledThreadPoolExecutor也和上面几种线程池一样返回的是ExecutorService接口的实现类ThreadPoolExecutor super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS, new DelayedWorkQueue()); }
可以使用有界队列,自定义线程创建工厂ThreadFactory和拒绝策略handler来自定义线程池
public class ThreadTest { public static void main(String[] args) throws InterruptedException, IOException { int corePoolSize = 2; int maximumPoolSize = 4; long keepAliveTime = 10; TimeUnit unit = TimeUnit.SECONDS; BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(2); ThreadFactory threadFactory = new NameTreadFactory(); RejectedExecutionHandler handler = new MyIgnorePolicy(); ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler); executor.prestartAllCoreThreads(); // 预启动所有核心线程 for (int i = 1; i <= 10; i++) { MyTask task = new MyTask(String.valueOf(i)); executor.execute(task); } System.in.read(); //阻塞主线程 } static class NameTreadFactory implements ThreadFactory { private final AtomicInteger mThreadNum = new AtomicInteger(1); @Override public Thread newThread(Runnable r) { Thread t = new Thread(r, "my-thread-" + mThreadNum.getAndIncrement()); System.out.println(t.getName() + " has been created"); return t; } } public static class MyIgnorePolicy implements RejectedExecutionHandler { @Override public void rejectedExecution(Runnable r, ThreadPoolExecutor e) { doLog(r, e); } private void doLog(Runnable r, ThreadPoolExecutor e) { // 可做日志记录等 System.err.println( r.toString() + " rejected"); // System.out.println("completedTaskCount: " + e.getCompletedTaskCount()); } } static class MyTask implements Runnable { private String name; public MyTask(String name) { this.name = name; } @Override public void run() { try { System.out.println(this.toString() + " is running!"); Thread.sleep(3000); //让任务执行慢点 } catch (InterruptedException e) { e.printStackTrace(); } } public String getName() { return name; } @Override public String toString() { return "MyTask [name=" + name + "]"; } } }
运行结果:
其中7-10号线程被拒绝策略拒绝了,1、2号线程执行完后,3、6号线程进入核心线程池执行,此时4、5号线程在任务队列等待执行,3、6线程执行完再通知4、5线程执行
The above is the detailed content of What are the four thread pools that come with Java?. For more information, please follow other related articles on the PHP Chinese website!