十七、ThreadPoolExecutor线程池

一、简介

JDK的Executor框架的实现类ThreadPoolExecutor,实现了Executor接口和ExecutorService接口。

ThreadPoolExecutor执行过程如下:

1)判断corePoolSize是否都执行中,如果不是那么直接执行任务。

2)判断缓冲队列是否满了,如果不是那么加入缓冲队列

3)判断是否超过maxNumPoolSize,如果不是那么创建线程执行任务。

4)如果超过maxNumPoolSize那么调用RejectedExecutionHandler

JDK文档:http://tool.oschina.net/uploads/apidocs/jdk-zh/java/util/concurrent/ThreadPoolExecutor.html

二、代码示例

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadPoolExecutorDemo {
    private static ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<>());

    public static void main(String[] args) {
        // 提交线程
        executor.submit(() -> System.out.println("running"));
        System.out.println("end");
    }
}
    

猜你喜欢

转载自www.cnblogs.com/lay2017/p/10166635.html