您的位置:首页 > 编程语言 > Java开发

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

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;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息