public class ThreadPoolKit extends Object
| 限定符和类型 | 方法和说明 |
|---|---|
static void |
execute(Runnable task)
提交一个 Runnable 任务到线程池任务队列,等待执行
在不需要返回值时,尽可能使用 execute,并用 try catch 对异常做好日志
以及处理好异常。
|
static ExecutorService |
getExecutor() |
static void |
init(ExecutorService executor)
传递 ExecutorService 对象进行初始化,从而完全掌控线程池参数
|
static void |
init(int nThreads)
初始化
|
static void |
shutdown()
等待正在执行的线程执行完毕以后,关闭线程池
|
static void |
shutdownNow()
停掉正在执行的线程,关闭线程池
|
static <T> Future<T> |
submit(Callable<T> task)
提交一个 Callable 任务到线程池任务队列,等待执行
调用返回值 Future 对象的 get() 方法,可获取到 Callable.call() 方法的返回值,除非有异常抛出
所以,该方法非常适用于需要得到 task 执行结果的场景
注意:submit(task).get(); 会阻塞当前线程直到 task 运行完毕
|
static Future<?> |
submit(Runnable task)
提交一个 Runnable 任务到线程池任务队列,等待执行
调用返回值 Future 对象的 get() 方法,始终返回 null,除非有异常抛出
下面的代码可以得到线程执行过程中抛出的异常,但会立即阻塞当前线程:
try {
submit(task).get();
} catch(Exception e){
...
}
|
static <T> Future<T> |
submit(Runnable task,
T result)
提交一个 Runnable 任务到线程池任务队列,等待执行
调用返回值 Future 对象的 get() 方法,始终返回 submit 方法的 result 参数值,除非有异常抛出
T result 参数无法在 Runnable 中被获取并使用,除非使用如下方式:
Ret result = Ret.create();
Future
|
public static void init(int nThreads)
nThreads - the number of threads in the poolpublic static void init(ExecutorService executor)
public static ExecutorService getExecutor()
public static void execute(Runnable task)
public static Future<?> submit(Runnable task)
public static <T> Future<T> submit(Runnable task, T result)
public static <T> Future<T> submit(Callable<T> task)
public static void shutdown()
public static void shutdownNow()
Copyright © 2022. All rights reserved.