您的位置:首页 > 其它

ExecutorService的几种关闭线程池方法

2016-03-31 15:48 477 查看
ExecutorService的几种关闭线程池方法:

ExecutorService executorService =Executors.newFixedThreadPool(1);

1、shutdown()方法在终止前允许执行以前提交的任务。 这个方法会顺次地关闭ExecutorService,当我们调用这个方法时,ExecutorService停止接受任何新的任务且等待已经提交的任务执行完成(已经提交的任务会分两类:一类是已经在执行的,另一类是还没有开始执行的),当所有已经提交的任务执行完毕后将会关闭ExecutorService。

Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted. Invocation has no additional effect if already shut down.

This method does not wait for previously submitted tasks to complete execution. Use
awaitTermination
to do that.

 2、shutdownNow()方法则是阻止正在任务队列中等待任务的启动并试图停止当前正在执行的任务,返回要停止的任务List。
 List<Runnable> shutdownNow();

Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution.

This method does not wait for actively executing tasks to terminate. Use
awaitTermination
to do that.

There are no guarantees beyond best-effort attempts to stop processing actively executing tasks. For example, typical implementations will cancel via
Thread.interrupt
, so any task that fails to respond to interrupts may never terminate.

Returns:list of tasks that never commenced execution
 3、awaitTermination方法:这个方法有两个参数,一个是timeout即超时时间,另一个是unit即时间单位。这个方法会使线程等待timeout时长,当超过timeout时间后,会监测ExecutorService是否已经关闭,若关闭则返回true,否则返回false。一般情况下会和shutdown方法组合使用。

Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.

Parameters:timeout the maximum time to waitunit the time unit of the timeout argumentReturns:
true
if this executor terminated and
false
if the timeout elapsed before terminationThrows:InterruptedException - if interrupted while waiting
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: