java多线程-线程池

创建线程需要操作系统资源(线程资源,栈空间等),频繁创建和销毁大量线程需要消耗大量时间。
那么我们就可以把很多小任务让一组线程来执行,而不是一个任务对应一个新线程。这种能接收大量小任务并进行分发处理的就是线程池。

newCachedThreadPool
ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i <= 3; i++) {
            int finalI = i;
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName() + "---我在飞==="+finalI);
                    if (finalI ==2){
                        try {
                            Thread.sleep(200);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                    }                }
            });
            Thread.sleep(100);
        }
        executorService.shutdown();

输出

pool-1-thread-1---我在飞===0
pool-1-thread-1---我在飞===1
pool-1-thread-1---我在飞===2
pool-1-thread-2---我在飞===3

可见在线程池中如果池内存在空闲线程,就会直接复用,如果没有就创建新的

newFixedThreadPool
ExecutorService executorService = Executors.newFixedThreadPool(2);
        for (int i = 0; i <= 3; i++) {
            int finalI = i;
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName() + "---我在飞===" + finalI);
                    try {
                        Thread.sleep(10000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();

                    }
                }
            });
        }
        executorService.shutdown();
pool-1-thread-1---我在飞===0
pool-1-thread-2---我在飞===1
此间隔10S
pool-1-thread-1---我在飞===3
pool-1-thread-2---我在飞===2

如果newFixedThreadPool池内无空闲线程他会等,不创建新线程

newSingleThreadExecutor

同newFixedThreadPool(1)

ThreadPoolExecutor

查看newSingleThreadExecutor源码

public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue()));
    }

创建线程池其实就是创建ThreadPoolExecutor对象

/**
     *
     * @param corePoolSize 核心线程数量
     * @param maximumPoolSize 最大线程数
     * @param keepAliveTime 空闲线程最大存活时间
     * @param unit 时间单位
     * @param workQueue 任务队列
     * @param threadFactory 创建线程的工厂
     * @param handler 任务的拒绝策略 超过最大线程数+任务队列最大长度
     */
    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler)

ThreadPoolExecutor.AbortPolicy 丢弃任务并抛出RejectedExecutionException异常(默认)
ThreadPoolExecutor.DiscardPolicy 丢弃任务 不抛出异常
ThreadPoolExecutor.DiscardOldestPolicy 抛弃队列中等待最久的任务 然后把当前任务加入到队列中
ThreadPoolExecutor.CallerRunsPolicy 调用任务的run()方法绕过线程池直接执行

你可能感兴趣的:(java多线程-线程池)