6.5.3 java预定义线程池CachedThreadPool 理解、使用示例

如果不了解线程池的各个参数的含义,可以查看此文章线程池的优点、以及各个参数的意义、使用示例

两个构造方法

 一个多了一个线程工厂的参数,能够对参数名等进行设置

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService executorService1 = Executors.newCachedThreadPool ();
        ExecutorService executorService2 = Executors.newCachedThreadPool( new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);
                thread.setName("我是newCachedThreadPool ,你来打我呀");
                return thread;
            }
        });
    }
}

构造理解

    public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }
  1. corePoolSize=0;maximumPoolSize=Integer.MAX_VALUE,最大会创建Integer.MAX_VALUE线程执行任务
  2. 等待时间默认是60秒,意味着空闲线程等待60无任务就会终止
  3. 使用CachedThreadPool无界阻塞队列,会不断创建线程

适用场景

适用于执行很多短期异步任务的小程序,或者负载较轻的服务器

使用demo

public class Test {
    static class Customer extends Thread {
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + "--开始执行");
            try {
                //模拟任务执行4s
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "--执行完成");
        }
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService executorService1 = Executors.newCachedThreadPool ();
        ExecutorService executorService2 = Executors.newCachedThreadPool( new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);
                thread.setName("我是newFixedThreadPool,你来打我呀");
                return thread;
            }
        });
        //执行普通没有返回值的任务,这两个任务会按照顺序执行
        for (int i = 0; i < 10; i++) {
            executorService1.execute(new Customer());
        }

        executorService1.execute(new Customer());
        //执行有返回值的任务
        Future submit = executorService1.submit(new Home(1, 10));
        System.out.println("get()方法会阻塞,直到拿到结果"+submit.get());
    }
}

结果:

pool-1-thread-1--开始执行
get()方法会阻塞,直到拿到结果55
我是newFixedThreadPool,你来打我呀--开始执行
get()方法会阻塞,直到拿到结果55
pool-1-thread-1--执行完成
我是newFixedThreadPool,你来打我呀--执行完成

 

 

 

 

 

 

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值