深入理解线程池

package com.example.juc;
import java.util.concurrent.*;

/**
 * @program: demo
 * @description: 线程池
 * @author: ZCY
 **/
public class ThreadPoolDemo {
    public static void main(String[] args) {
        //本质都是调用ThreadPoolExecutor    三大方法,7大参数,4种策略
        ExecutorService threadPool = null;
        ExecutorService threadPool2 = null;
        ExecutorService threadPool3 = null;
        try {
            threadPool = Executors.newCachedThreadPool(); //大小可变
            threadPool2 = Executors.newSingleThreadExecutor();//只有一个核心线程
            threadPool3 = Executors.newFixedThreadPool(5);//固定线程数
            for (int i = 1; i <= 6; i++) {
                threadPool3.execute(() -> {
                    System.out.println(Thread.currentThread().getName() + "---OK");
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            threadPool3.shutdown();
        }
    }
}
     
class ThreadPoolDemo2 {
    public static void main(String[] args) {
        //自定义创建线程池
        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(
                2,  //核心线程数
                5,  //最大线程数
                10,  //超时时间
                TimeUnit.SECONDS,  //超时单位
                new ArrayBlockingQueue<>(4), //阻塞队列
                Executors.defaultThreadFactory(),     //线程工厂
                new ThreadPoolExecutor.CallerRunsPolicy()  //拒绝策略
        );
        //四种拒绝策略
        //ThreadPoolExecutor.AbortPolicy() 抛出异常
        //ThreadPoolExecutor.DiscardPolicy() 不抛出异常,直接放弃任务
        //ThreadPoolExecutor.DiscardOldestPolicy() 不抛出异常,将队列首的任务放弃,加入新任务
        //ThreadPoolExecutor.CallerRunsPolicy() 请求从哪里来回哪里去 由main线程执行
        //RejectedExecutionException
        for (int i = 0; i < 9; i++) {
            poolExecutor.execute(() -> {
                System.out.println(Thread.currentThread().getName() + "--OK");
            });
            //System.out.println(Thread.activeCount());
            //System.out.println("------------------");
        }
        poolExecutor.shutdown();
        //最大线程如何定义
        //System.out.println(Runtime.getRuntime().availableProcessors());
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值