线程池

线程池

线程池

public static void main(String[] args) throws InterruptedException {
        // 1. 创建一个默认的线程池对象,池子默认是空的,默认最多可以容纳int类型的最大值
        ExecutorService executorService = Executors.newCachedThreadPool();
        //Executors --- 可以帮助我们创建线程池对象
        //ExecutorService --- 可以帮助我们控制线程池

        executorService.submit(() ->{
            System.out.println(Thread.currentThread().getName() + "在执行了");
        });

        Thread.sleep(2000);

        executorService.submit(() ->{
            System.out.println(Thread.currentThread().getName() + "在执行了");
        });

        executorService.shutdown();
    }
public static void main(String[] args) {
        // static ExecutorService newFixedThreadPool(int nThreads)
        // 创建一个指定最多线程数量的线程池
        // 参数不是初始值而是最大值
        // ExecutorService是ThreadPoolExecutor实现的接口
        ExecutorService executorService = Executors.newFixedThreadPool(10);

        ThreadPoolExecutor pool = (ThreadPoolExecutor) executorService;
        System.out.println(pool.getPoolSize());

        executorService.submit(() -> {
            System.out.println(Thread.currentThread().getName() + "在执行了");
        });

        executorService.submit(() -> {
            System.out.println(Thread.currentThread().getName() + "在执行了");
        });

        System.out.println(pool.getPoolSize());

        executorService.shutdown();
    }

创建线程池对象

ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(核心线程数量,最大线程数量,空闲线程最大存活时间,任务队列,创建线程工厂,任务的拒绝策略)

ThreadPoolExecutor (int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler)

任务拒绝策略

new ThreadPoolExecutor.AbortPolicy() 默认策略,

new ThreadPoolExecutor.DiscardPolicy() 丢弃任务,但是不抛出异常,这是不推荐的做法

new ThreadPoolExecutor.DiscardOlderstPolicy() 抛弃队列中等待最久的任务然后把当前任务加入队列中

new ThreadPoolExecutor.CallerRunsPolicy() : 调用任务的run()方法绕过线程池直接执行。交给别人去执行

public class MyThreadPoolDemo4 {
    // 参数一:核心线程数量
    // 参数二:最大线程数
    // 参数三:空闲线程最大存活时间
    // 参数四:时间单位
    // 参数五:任务队列   -- 让任务在队列中等待,等线程空闲了,再从这个队列中获取任务并执行
    // 参数六:创建线程工厂 --- 按照默认的方式创建线程对象
    // 参数七:任务的拒绝策略  --- 1. 什么时候拒绝任务 当提交的任务 > 池子中最大线程数量 + 任务队列的容量
                            // 2. 如何拒绝 AbortPolicy 丢弃任务并抛出异常
    public static void main(String[] args) {
        ThreadPoolExecutor pool = new ThreadPoolExecutor(
                2,
                5,
                2,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(10),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());
        pool.submit(new MyRunnable());
        pool.submit(new MyRunnable());

        pool.shutdown();

    }
}