Executors线程池

线程使用上的常见问题

  • new Thread().start()
  1. 线程的繁忙创建和销毁
  2. 线程的数据过多,会导致CPU资源的上下文切换开销问题

java中提供的四种常见的线程池

  1. newFixedThreadPool :固定线程数量
public static ExecutorService newFixedThreadPool(int nThreads) {
   
    return new ThreadPoolExecutor(nThreads, nThreads,
                                  0L, TimeUnit.MILLISECONDS,
                                  new LinkedBlockingQueue<Runnable>());
}
  1. newSingleThreadExecutor :只有一个线程的线程池
public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) {
   
    return new FinalizableDelegatedExecutorService
        (new ThreadPoolExecutor(1, 1,
                                0L, TimeUnit.MILLISECONDS,
                                new LinkedBlockingQueue<Runnable>(),
                                threadFactory));
}
  1. newCachedThreadPool :可缓存的线程池 -> 理论上说有多少个请求就可以创建多少个线程来处理
public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
   
    return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                  60L, TimeUnit.SECONDS,
                                  new SynchronousQueue<Runnable>(),
                                  threadFactory);
}
  1. newScheduledThreadPool :提供指定周期执行的线程池
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
   
    return new ScheduledThreadPoolExecutor(corePoolSize);
}

实现线程复用原理拆解

  • 实现线程重复使用的唯一方法就是让线程一直运行中
  • 线程一直运行中如何获取新的任务呢,【可以使用共享队列AQS,让所有线程从里面获取任务】
  • 考虑到如果没有任务的时候让线程停止,避免浪费cpu。有任务唤醒,没有任务着阻塞,类似一个生产者和消费者关系【可以使用LinkedBlockingQueue,获取任务】
  • 拒绝策略:在队列已满的情况下如何处理
    在这里插入图片描述

ExecutorService.execute() 底层原理

public void execute(Runnable command) {
   
    if (command == null)
        throw new NullPointerException();
    int c = ctl.get();    // 获取当前线程池创建线程
    if (workerCountOf(c) < corePoolSize
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值