线程池入门

线程池的简单使用

public class TestThreadPool {
    /**
     * 一、线程池:提供了一个线程队列,队列中保存着所有等待状态的线程。避免了创建与销毁额外开销,提高了响应的速度。
     * 二、线程池的体系结构:
     * java.util.concurrent.Executor :负责线程的使用与调度的根接口
     *       --**ExecutorService子接口:线程池的主要接口
     *         --ThreadPoolExecutor线程池的实现类
     *             --ScheduledExecutorService子接口:负责线程的调度
     *                --ScheduledThreadPoolExecutor:继承ThreadPoolExecutor,实现ScheduledExecutorService
     * 三、工具类: Executors
     * ExecutorService newFixedThreadPool():创建固定大小的线程池。
     * ExecutorService newCachedThreadPoo1():缓存线程池,线程池的数量不固定,可以根据需求自动的更改数量。
     * ExecutorService newSingleThreadExecutor():创建单个线程池。线程池中只有一个线程。
     *
     * ScheduledExecutorService newScheduledThreadPool():创建固定大小的线程,可以延迟或定时的执行任务。
     */
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        ThreadPool tp = new ThreadPool();
        //为线程池分配任务
        executorService.submit(tp);

        Future<Integer> submit = executorService.submit(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                int sum = 0;
                for (int i = 0; i < 50; i++) {
                    sum += i;
                }
                return sum;
            }
        });
        //输出值
        System.out.println(submit.get());

        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(5);
        Future<Integer> submit2 = scheduledExecutorService.schedule(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                int sum = 0;
                for (int i = 0; i < 50; i++) {
                    sum += i;
                }
                return sum;
            }
        },6, TimeUnit.SECONDS);
        //输出值
        System.out.println(submit2.get());

        scheduledExecutorService.shutdown();
        executorService.shutdown();
    }
}
class ThreadPool implements Runnable {
    private int i = 0;
    @Override
    public void run() {
        while (i < 10) {
            System.out.println(Thread.currentThread().getName() + "::::" + ++i);
        }
    }
}

submit和execute

  1. execute没有返回值
  2. submit有返回值
  3. excute方法会抛出异常。
  4. sumbit方法不会抛出异常,除非你调用Future.get()。

自定义线程池

   public ThreadPoolExecutor(int corePoolSize,//核心线程池大小
                             int maximumPoolSize,//最大核心线程池大小
                             long keepAliveTime,//超过核心线程数的线程超时 时,没有人调用就会释放此线程
                             TimeUnit unit,//超时单位
                             BlockingQueue<Runnable> workQueue,//阻塞队列
                             ThreadFactory threadFactory,//创建线程工厂
                             RejectedExecutionHandler handler) //拒绝策略
  
    public static void main(String[] args) {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                3,
                5,
                3,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());
        try {
            for (int i = 0; i < 10; i++) {
                threadPoolExecutor.execute(() -> {
                    System.out.println(Thread.currentThread().getName() + " OK");
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            threadPoolExecutor.shutdown();
        }
    }
//拒绝策略   
1new ThreadPoolExecutor.AbortPolicy() 线程池占用满了,还有人进来,则抛异常RejectedExecutionException
pool-1-thread-2 OK
pool-1-thread-2 OK
pool-1-thread-2 OK
pool-1-thread-2 OK
pool-1-thread-3 OK
pool-1-thread-5 OK
pool-1-thread-1 OK
pool-1-thread-4 OK
java.util.concurrent.RejectedExecutionException: Task
2new ThreadPoolExecutor.CallerRunsPolicy() 哪来的回哪
main OK //这里可以看出main线程执行的
main OK
pool-1-thread-1 OK
pool-1-thread-1 OK
pool-1-thread-1 OK
pool-1-thread-1 OK
pool-1-thread-2 OK
pool-1-thread-3 OK
pool-1-thread-4 OK
pool-1-thread-5 OK
3new ThreadPoolExecutor.DiscardPolicy() 队列满了,不抛异常,直接丢掉
pool-1-thread-1 OK //可以看出打印的信息条数变少
pool-1-thread-1 OK
pool-1-thread-1 OK
pool-1-thread-1 OK
pool-1-thread-2 OK
pool-1-thread-3 OK
pool-1-thread-4 OK
pool-1-thread-5 OK
4new ThreadPoolExecutor.DiscardOldestPolicy() 队列满了,不抛异常,尝试和最早的竞争
pool-1-thread-1 OK
pool-1-thread-1 OK
pool-1-thread-1 OK
pool-1-thread-1 OK
pool-1-thread-2 OK
pool-1-thread-3 OK
pool-1-thread-4 OK
pool-1-thread-5 OK

最大线程到底该如何定义
1、CPU密集型,几核,就是几,可以保持CPU的效率最高
2、IO密集型>判断你程序中十分耗IO的线程,
example:程序10个大型任务io十分占用资源!,可以设置15~20,保证其他线程正常使用。

获取cpu核心数
 System.out.println(Runtime.getRuntime().availableProcessors());
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值