2020最新Java线程池入门(超详细)

转 https://blog.csdn.net/weixin_43893397/article/details/104361154

【1】代码示例 

/**
 * 线程池测试-自定义线程池创建方式
 * @since 2021/03/23 
 */
public class ThreadPoolMain2 {
	public static void main(String[] args) throws Exception {
		newMethod();
	}
	
	public static void newMethod() throws InterruptedException {
        /**
         * 开启一个线程池  默认线程是10个
         * 使用默认线程工厂
         * 拒绝策略为CallerRunsPolicy策略,让后面的线程先等待 
         */
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
        		10
        		, 10
        		, 1000L
        		, TimeUnit.MILLISECONDS
        		, new ArrayBlockingQueue(10)
        		,Executors.defaultThreadFactory()
        		,new ThreadPoolExecutor.CallerRunsPolicy());
            //书写一个循环  模拟100个用户同时访问
            for (int request = 0; request< 100;request ++){
            	final int temp = request; 
                //开启一个线程
                threadPoolExecutor.execute(() ->{
                    System.out.println("任务" + temp +"开始执行...");
                    /**
                     * 睡10秒 
                     */
                    try {
                        Thread.sleep(1000L * 3);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("任务" + temp +"执行结束...");
                });
            }
    }
}

【2】 ThreadPoolExecutor 构造器解析

/**
     * Creates a new {@code ThreadPoolExecutor} with the given initial
     * parameters.
     *
     * @param corePoolSize the number of threads to keep in the pool, even
     *        if they are idle, unless {@code allowCoreThreadTimeOut} is set
     * @param maximumPoolSize the maximum number of threads to allow in the
     *        pool
     * @param keepAliveTime when the number of threads is greater than
     *        the core, this is the maximum time that excess idle threads
     *        will wait for new tasks before terminating.
     * @param unit the time unit for the {@code keepAliveTime} argument
     * @param workQueue the queue to use for holding tasks before they are
     *        executed.  This queue will hold only the {@code Runnable}
     *        tasks submitted by the {@code execute} method.
     * @param threadFactory the factory to use when the executor
     *        creates a new thread
     * @param handler the handler to use when execution is blocked
     *        because the thread bounds and queue capacities are reached
     * @throws IllegalArgumentException if one of the following holds:
* {@code corePoolSize < 0}
* {@code keepAliveTime < 0}
* {@code maximumPoolSize <= 0}
* {@code maximumPoolSize < corePoolSize} * @throws NullPointerException if {@code workQueue} * or {@code threadFactory} or {@code handler} is null */ public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) {

【3】参数解析

序号 参数名 描述 中文
1 corePoolSize the number of threads to keep in the pool, even if they are idle, unless {@code allowCoreThreadTimeOut} is set. 除非设置了{@code allowCoreThreadTimeOut},否则即使它们处于空闲状态也要保留在池中的线程数。
2 maximumPoolSize  the maximum number of threads to allow in the pool 池中允许的最大线程数
3 keepAliveTime when the number of threads is greater than the core, this is the maximum time that excess idle threads will wait for new tasks before terminating. 当线程数大于内核数时,这是多余的空闲线程将在终止之前等待新任务的最长时间。
4 unit the time unit for the {@code keepAliveTime} argument {@code keepAliveTime}参数的时间单位
5 workQueue

 the queue to use for holding tasks before they are executed. This queue will hold only the Runnable tasks submitted by the execute method.

在执行任务之前用于保留任务的队列。 此队列将仅保存execute方法提交的Runnable任务。
6 threadFactory the factory to use when the executorcreates a new thread. 执行程序创建新线程时要使用的工厂。
7 handler

 the handler to use when execution is blockedbecause the thread bounds and queue capacities are reached.

当执行被阻塞时使用的处理程序,因为达到了线程界限和队列容量。

【4】抛弃策略

// 当任务无法添加到阻塞队列时的处理策略-直接抛出异常
		RejectedExecutionHandler rejectHandler1 = new ThreadPoolExecutor.AbortPolicy(); 
		// -会调用当前线程池的所在的线程去执行被拒绝的任务。
		RejectedExecutionHandler rejectHandler2 = new ThreadPoolExecutor.CallerRunsPolicy(); 
		// 会抛弃任务队列中最旧的任务也就是最先加入队列的,再把这个新任务添加进去。
		RejectedExecutionHandler rejectHandler3 = new ThreadPoolExecutor.DiscardOldestPolicy();
		// 会让被线程池拒绝的任务直接抛弃,不会抛异常也不会执行。
		RejectedExecutionHandler rejectHandler4 = new ThreadPoolExecutor.DiscardPolicy(); 
		
		RejectedExecutionHandler rejectHandler = rejectHandler4; 
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
        		10
        		, 10
        		, 1000L
        		, TimeUnit.MILLISECONDS
        		, new ArrayBlockingQueue(10)
        		,Executors.defaultThreadFactory()
        		, rejectHandler);

 

 

 

 

你可能感兴趣的:(ThinkinginJava,java)