java 線程池 Executor 體系概要
資料來源於 JDK 1.8 API
UML
Executor 執行器
public interface Executor {
void execute(Runnable command);
}
ExecutorService
核心方法
public interface ExecutorService extends Executor {
/**
提交值返回任務以執行,並返回代表任務待處理結果的Future。 未來的get方法將在成功完成後返回任務的結果。
如果您想立即阻止等待任務,您可以使用result = exec.submit(aCallable).get();格式的result = exec.submit(aCallable).get();
注意: Executors類包括一組方法,可以將一些其他常見的類似對象的對象,例如PrivilegedAction轉換爲Callable表單,以便它們可以提交。
*/
<T> Future<T> submit(Callable<T> task);
/**
提交一個可運行的任務執行,並返回一個表示該任務的未來。 未來的get方法將在成功完成後返回給定的結果。
*/
<T> Future<T> submit(Runnable task, T result);
/**
提交一個可運行的任務執行,並返回一個表示該任務的未來。 未來的get方法將返回null 成功完成時。
*/
Future<?> submit(Runnable task);
}
Executors 工具類
public class Executors {
/** Cannot instantiate. */
private Executors() {}
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(),
threadFactory);
}
public static ExecutorService newWorkStealingPool() {
return new ForkJoinPool
(Runtime.getRuntime().availableProcessors(),
ForkJoinPool.defaultForkJoinWorkerThreadFactory,
null, true);
}
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
public static ScheduledExecutorService newSingleThreadScheduledExecutor() {
return new DelegatedScheduledExecutorService
(new ScheduledThreadPoolExecutor(1));
}
public static ExecutorService unconfigurableExecutorService(ExecutorService executor) {
if (executor == null)
throw new NullPointerException();
return new DelegatedExecutorService(executor);
}
public static ThreadFactory defaultThreadFactory() {
return new DefaultThreadFactory();
}
public static ThreadFactory privilegedThreadFactory() {
return new PrivilegedThreadFactory();
}
public static <T> Callable<T> callable(Runnable task, T result) {}
public static Callable<Object> callable(Runnable task) {}
}
ThreadFactory 線程工廠
/**
class SimpleThreadFactory implements ThreadFactory {
public Thread newThread(Runnable r) {
return new Thread(r);
}
}}
*/
public interface ThreadFactory {
Thread newThread(Runnable r);
}