Executors的四种线程池的使用场景

1、Executors.newCacheThreadPool():

创建一个可缓存的线程池。如果线程池的大小超过了处理任务所需要的线程,那么就会回收部分空闲(60 秒不执行任务)的线程,当任务数增加时,此线程池又可以智能的添加新线程来处理任务。此线程池不会对线程池大小做限制,线程池大小完全依赖于操作系统(或者说 JVM)能够创建的 大线程大小。

缓存型池子通常用于执行一些生存期很短的异步型任务。

public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, 2147483647, 60L, TimeUnit.SECONDS, new SynchronousQueue());
 }
  @Test
    public void test01() throws InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        for(int i=0; i<10; i++){
            //sleep可明显看到使用的是线程池里面以前的线程,线程的名字都是一样的,没有创建新的线程
            Thread.sleep(1000);
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName() + "正在被执行");
                }
            });
        }
    }

结果:

pool-1-thread-1正在被执行
pool-1-thread-1正在被执行
pool-1-thread-1正在被执行
pool-1-thread-1正在被执行
pool-1-thread-1正在被执行
pool-1-thread-1正在被执行
pool-1-thread-1正在被执行
pool-1-thread-1正在被执行
pool-1-thread-1正在被执行
pool-1-thread-1正在被执行

2、Executors.newFixedThreadPool(int n):

创建固定大小的线程池。每次提交一个任务就创建一个线程,直到线程达到线程池的 大大小。线程池的大小一旦达到 大值就会保持不变,如果某个线程因为执行异常而结束,那么线程池会补充一个新线程。如果希望在服务器上使用线程池,建议使用 newFixedThreadPool方法来创建线程池,这样能获得更好的性能。以共享的无界队列方式来运行这些线程。

public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue());
    }
   @Test
    public void test02() throws InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        for(int i=0; i<10; i++){
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName() + "正在被执行");
                }
            });
        }
    }

结果:

pool-1-thread-1正在被执行
pool-1-thread-2正在被执行
pool-1-thread-2正在被执行
pool-1-thread-2正在被执行
pool-1-thread-2正在被执行
pool-1-thread-2正在被执行
pool-1-thread-2正在被执行
pool-1-thread-2正在被执行
pool-1-thread-2正在被执行
pool-1-thread-3正在被执行

3、Executors.newScheduledThreadPool(int n):

创建一个固定大小的线程池。此线程池支持定时以及周期性执行任务的需求。

public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
        return new ScheduledThreadPoolExecutor(corePoolSize);
    }
 public ScheduledThreadPoolExecutor(int corePoolSize) {
        super(corePoolSize, 2147483647, 10L, TimeUnit.MILLISECONDS, new ScheduledThreadPoolExecutor.DelayedWorkQueue());
    }
	public static void main(String[] args) {
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(3);
        System.out.println("执行前时间:" + System.currentTimeMillis());
        scheduledExecutorService.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("执行时时间:" + System.currentTimeMillis());
                System.out.println(Thread.currentThread().getName() + "正在被执行-延迟1秒执行");
            }
        }, 1, TimeUnit.SECONDS);
        scheduledExecutorService.shutdown();
    }

结果:

执行前时间:1678422253924
执行时时间:1678422254939
pool-1-thread-1正在被执行-延迟1秒执行

4、Executors.newSingleThreadExecutor():

创建一个单线程的线程池。这个线程池只有一个线程在工作,也就是相当于单线程串行执行所有任务。如果这个唯一的线程因为异常结束,那么会有一个新的线程来替代它。此线程池保证所有任务的执行顺序按照任务的提交顺序执行。

public static ExecutorService newSingleThreadExecutor() {
        return new Executors.FinalizableDelegatedExecutorService(new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue()));
    }
    @Test
    public void test03() throws InterruptedException {
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        for(int i=0; i<10; i++){
            final int finalI = i;
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    结果依次输出,相当于顺序执行各个任务
                    System.out.println(Thread.currentThread().getName() + "正在被执行" + String.valueOf(finalI));
                }
            });
        }
    }

结果:

pool-1-thread-1正在被执行0
pool-1-thread-1正在被执行1
pool-1-thread-1正在被执行2
pool-1-thread-1正在被执行3
pool-1-thread-1正在被执行4
pool-1-thread-1正在被执行5
pool-1-thread-1正在被执行6
pool-1-thread-1正在被执行7
pool-1-thread-1正在被执行8
pool-1-thread-1正在被执行9

如有不对的地方,敬请指出。

点击关注,带你了解更多

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值