整理了一下线程池经常用到的方法:
//是否正在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,连接:
还没写好,稍等。。。