Java并发编程——线程池的使用(六)线程池的常用方法

整理了一下线程池经常用到的方法:

//是否正在shutdown()
executor.isTerminating();
//是否已经shutdown()
executor.isTerminated();
//在3秒内是否shutdown(),如果不调用shutdown(),在线程池中仍有任务时,会有堵塞效果(时间结束或任务结束释放)
boolean b = executor.awaitTermination(3, TimeUnit.SECONDS);
//允许核心线程超时
executor.allowsCoreThreadTimeOut();
executor.allowCoreThreadTimeOut(true);
//增加一条核心线程,但不能超过核心线程最大值,返回是否成功
boolean b = executor.prestartCoreThread();
//启动全部核心线程,返回核心线程的数量
int i = executor.prestartAllCoreThreads();
//获取完成的任务数
executor.getCompletedTaskCount();
//重写beforeExecute和afterExecute  任务执行前,任务执行完成

//移除未进行的任务是否成功   executor.submit()提交的任务不可移除
boolean remove = executor.remove(Runnable);
//获取正在进行任务的线程数量
executor.getActiveCount();

关于执行Callable的方法:

List<Callable<String>> list = new ArrayList<>();
list.add(new MyCallable("123"));
list.add(new MyCallable("456"));
list.add(new MyCallable("789"));
//执行list里的所有任务,并返回第一个执行完毕的结果
String s = executor.invokeAny(list);
//执行list里的所有任务,并在3秒内返回第一个执行完毕的结果
String s = executor.invokeAny(list, 3, TimeUnit.SECONDS);
//按顺序执行list里的任务,阻塞进程,所有任务执行完毕并返回结果
List<Future<String>> s = executor.invokeAll(list);
//按顺序执行list里的任务,阻塞进程,3秒内所有任务执行完毕并返回结果,调用Future.get()方法不再阻塞
List<Future<String>> s = executor.invokeAll(list, 3, TimeUnit.SECONDS);

这里写的不是很详细,因为我想另起一篇博客写下Future和Callable,连接:
还没写好,稍等。。。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值