java 线程池

线程池的状态

ThreadPoolExecutor 使用int的高3位来表示线程池的状态,低29位标识线程数量

状态名高三位接收新任务处理阻塞队列任务说明
running111YY
shutdown000NY
stop001NN
tidying010过度状态,任务全部执行完毕
terminated011终结状态

ThreadPoolExecutor的构造方法

ThreadPoolExecutor(int corePoolSize, //核心线程数
                   int maximumPoolSize, //最大线程数
                   long keepAliveTime, //救急线程等待时间
                   TimeUnit unit,//时间单位
                   BlockingQueue<Runnable> workQueue, //阻塞队列
                   ThreadFactory threadFactory, //线程工厂,可以为线程创建时取好名字
                   RejectedExecutionHandler handler//拒绝策略
                   )

固定大小的线程池

public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                   0L, TimeUnit.MILLISECONDS,
                    new LinkedBlockingQueue<Runnable>());
}

单线程线程池

public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
             0L, TimeUnit.MILLISECONDS,
             new LinkedBlockingQueue<Runnable>()));
}

带缓冲线程池

public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
               60L, TimeUnit.SECONDS,
               new SynchronousQueue<Runnable>());
}

submit() : 可以获取执行结果

    public static void test4() {
        ThreadPoolExecutor pool=(ThreadPoolExecutor) Executors.newFixedThreadPool(2);
        Future<String> future = executorService.submit(() -> "ok");
        System.out.println("main ==>" + future.get());
    }

invokeAll()

List<Future<Object>> futures = 
			pool.invokeAll(Arrays.asList(() -> "1", 
						() -> "2", 
						() -> "3")
			);
futures.forEach(f -> System.out.println(f.get()));

invokeAny() 返回一个最先得到结果的任务

Object o = pool.invokeAny(Arrays.asList(() -> "1", () -> "2"));
            System.out.println(o);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值