Java线程池,shutdown、awaitTermination、shutdownNow的作用与区别
2018-01-28 18:06
405 查看
shutdown方法:平滑的关闭ExecutorService,当此方法被调用时,ExecutorService停止接收新的任务并且等待已经提交的任务(包含提交正在执行和提交未执行)执行完成。
当所有已提交任务执行完毕,线程池即被关闭。
awaitTermination方法:接收timeout和unit两个参数,用于设定超时时间及单位。当等待超过设定时间时,会监测ExecutorService是否已经关闭,
若关闭则返回true,否则返回false。一般情况下会和shutdown方法组合使用。
shutdown调用后,不可以再submit新的task,已经submit的将继续执行。
shutdownNow试图停止当前正执行的task,并返回尚未执行的task的list
英文好的可继续参考源码:
/**
* 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.
*
* <p>This method does not wait for previously submitted tasks to
* complete execution. Use {@link #awaitTermination awaitTermination}
* to do that.
*
* @throws SecurityException if a security manager exists and
* shutting down this ExecutorService may manipulate
* threads that the caller is not permitted to modify
* because it does not hold {@link
* java.lang.RuntimePermission}{@code ("modifyThread")},
* or the security manager's {@code checkAccess} method
* denies access.
*/
void shutdown();
当所有已提交任务执行完毕,线程池即被关闭。
awaitTermination方法:接收timeout和unit两个参数,用于设定超时时间及单位。当等待超过设定时间时,会监测ExecutorService是否已经关闭,
若关闭则返回true,否则返回false。一般情况下会和shutdown方法组合使用。
shutdown调用后,不可以再submit新的task,已经submit的将继续执行。
shutdownNow试图停止当前正执行的task,并返回尚未执行的task的list
import java.util.concurrent.Callable; /** * Title: ShortTask * Description: * @date 2018/1/28 17:32 */ public class ShortTask implements Callable { @Override public Object call() throws Exception { System.out.println("短任务"); return null; } }
import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; /** * Title: LongTask * Description: * @date 2018/1/28 17:33 */ public class LongTask implements Callable { @Override public Object call() throws Exception { System.out.println("长任务"); TimeUnit.SECONDS.sleep(5); return null; } }
import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class Main { public static void main(String[] args) { ScheduledExecutorService service = Executors.newScheduledThreadPool(4); service.submit(new ShortTask()); service.submit(new ShortTask()); service.submit(new LongTask()); service.submit(new ShortTask()); service.shutdown(); // List<Runnable> list = service.shutdownNow(); // System.out.println(list.size()); try { while (!service.awaitTermination(1, TimeUnit.SECONDS)) { System.out.println("线程池没有关闭"); } } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("线程池已经关闭"); } } /*service.shutdown(); 短任务 短任务 长任务 短任务 线程池没有关闭 线程池没有关闭 线程池没有关闭 线程池没有关闭 线程池已经关闭*/ /* List<Runnable> list = service.shutdownNow(); System.out.println(list.size()); 短任务 短任务 长任务 1 线程池已经关闭 */
英文好的可继续参考源码:
/**
* 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.
*
* <p>This method does not wait for previously submitted tasks to
* complete execution. Use {@link #awaitTermination awaitTermination}
* to do that.
*
* @throws SecurityException if a security manager exists and
* shutting down this ExecutorService may manipulate
* threads that the caller is not permitted to modify
* because it does not hold {@link
* java.lang.RuntimePermission}{@code ("modifyThread")},
* or the security manager's {@code checkAccess} method
* denies access.
*/
void shutdown();
/** * Attempts to stop all actively executing tasks, halts the * processing of waiting tasks, and returns a list of the tasks * that were awaiting execution. * * <p>This method does not wait for actively executing tasks to * terminate. Use {@link #awaitTermination awaitTermination} to * do that. * * <p>There are no guarantees beyond best-effort attempts to stop * processing actively executing tasks. For example, typical * implementations will cancel via {@link Thread#interrupt}, so any * task that fails to respond to interrupts may never terminate. * * @return list of tasks that never commenced execution * @throws SecurityException if a security manager exists and * shutting down this ExecutorService may manipulate * threads that the caller is not permitted to modify * because it does not hold {@link * java.lang.RuntimePermission}{@code ("modifyThread")}, * or the security manager's {@code checkAccess} method * denies access. */ List<Runnable> shutdownNow();
/** * Blocks until all tasks have completed execution after a shutdown * request, or the timeout occurs, or the current thread is * interrupted, whichever happens first. * * @param timeout the maximum time to wait * @param unit the time unit of the timeout argument * @return {@code true} if this executor terminated and * {@code false} if the timeout elapsed before termination * @throws InterruptedException if interrupted while waiting */ boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException;
相关文章推荐
- Java线程池,isShutDown、isTerminated的作用与区别
- 线程池中shutdown()和shutdownNow()方法的区别
- JAVA shutdown和shutdownNow的区别
- threadPoolExecutor 中的 shutdown() 、 shutdownNow() 、 awaitTermination() 的用法和区别
- 基于Java的打包jar、war、ear包的作用与区别详解
- OpenJDK源码研究笔记(二)-Comparable和Comparator2个接口的作用和区别(一道经典的Java笔试面试题)
- (转)Java 之 FileReader FileInputStream InputStreamReader BufferedReader 作用与区别
- ExecutorService对象的shutdown()和shutdownNow()的区别
- java弱引用(WeakReference)和SoftReference的区别以及在android内存处理的作用
- 面试题-Java作用域描述符的区别
- java弱引用(WeakReference)和SoftReference的区别以及在android内存处理的作用
- JAVA线程池shutdown和shutdownNow的区别
- Java中volatile和synchronized 作用以及区别
- 基于Java的打包jar、war、ear包的作用与区别详解
- OpenJDK源码研究笔记(二)-Comparable和Comparator2个接口的作用和区别(一道经典的Java笔试面试题)
- Java基础之hashCode()的作用,以及==、equals()和hashCode()区别
- JAVA线程池shutdown和shutdownNow的区别
- Java中length,length()与size()的作用与区别
- 转载:java中抽象类和接口的作用与区别
- java中四种线程池的区别