public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>()); }
public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); }
public static ExecutorService newSingleThreadExecutor() { return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())); }
private static final RejectedExecutionHandler defaultHandler = new AbortPolicy(); public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) { this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, Executors.defaultThreadFactory(), defaultHandler); }
public interface ExecutorService extends Executor { void shutdown(); List<Runnable> shutdownNow(); boolean isShutdown(); boolean isTerminated(); boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException; // 省略部分方法
}
submit() 與execute()區別數據庫
一、接收的參數不同 緩存
submit()能夠接受runnable無返回值和callable有返回值
execute()接受runnable 無返回值多線程
二、submit有返回值,而execute沒有架構
Method submit extends base method Executor.execute by creating and returning a Future that can be used to cancel execution and/or wait for completion.app
用到返回值的例子,好比說我有不少個作validation的task,我但願全部的task執行完,而後每一個task告訴我它的執行結果,是成功仍是失敗,若是是失敗,緣由是什麼。dom
三、submit方便Exception處理異步
There is a difference when looking at exception handling. If your tasks throws an exception and if it was submitted with execute this exception will go to the uncaught exception handler (when you don’t have provided one explicitly, the default one will just print the stack trace to System.err). If you submitted the task with submit any thrown exception, checked or not, is then part of the task’s return status. For a task that was submitted with submit and that terminates with an exception, the Future.get will rethrow this exception, wrapped in an ExecutionException.ide
意思就是若是你在你的task裏會拋出checked或者unchecked exception,而你又但願外面的調用者可以感知這些exception並作出及時的處理,那麼就須要用到submit,經過捕獲Future.get拋出的異常。this
public class ExecutorServiceTest { public static void main(String[] args) { ExecutorService executorService = Executors.newCachedThreadPool(); List<Future<String>> resultList = new ArrayList<Future<String>>(); // 建立10個任務並執行 for (int i = 0; i < 10; i++) { // 使用ExecutorService執行Callable類型的任務,並將結果保存在future變量中 Future<String> future = executorService.submit(new TaskWithResult(i)); // 將任務執行結果存儲到List中 resultList.add(future); } executorService.shutdown(); // 遍歷任務的結果 for (Future<String> fs : resultList) { try { System.out.println(fs.get()); // 打印各個線程(任務)執行的結果 } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } finally {
executorService.shutdownNow();
} } } } class TaskWithResult implements Callable<String> { private int id; public TaskWithResult(int id) { this.id = id; } /** * 任務的具體過程,一旦任務傳給ExecutorService的submit方法,則該方法自動在一個線程上執行。 * * @return * @throws Exception */ public String call() throws Exception { System.out.println("call()方法被自動調用,幹活!!! " + Thread.currentThread().getName()); if (new Random().nextBoolean()) throw new TaskException("Meet error in task." + Thread.currentThread().getName()); // 一個模擬耗時的操做 for (int i = 999999999; i > 0; i--) ; return "call()方法被自動調用,任務的結果是:" + id + " " + Thread.currentThread().getName(); } } class TaskException extends Exception { public TaskException(String message) { super(message); } }
1. private final BlockingQueue<Runnable> workQueue; // 阻塞隊列
2. private final ReentrantLock mainLock = new ReentrantLock(); // 互斥鎖
3. private final HashSet<Worker> workers = new HashSet<Worker>();// 線程集合.一個Worker對應一個線程
4. private final Condition termination = mainLock.newCondition();// 終止條件
5. private int largestPoolSize; // 線程池中線程數量曾經達到過的最大值。
6. private long completedTaskCount; // 已完成任務數量
7. private volatile ThreadFactory threadFactory; // ThreadFactory對象,用於建立線程。
8. private volatile RejectedExecutionHandler handler;// 拒絕策略的處理句柄
9. private volatile long keepAliveTime; // 線程池維護線程所容許的空閒時間
10. private volatile boolean allowCoreThreadTimeOut; 11. private volatile int corePoolSize; // 線程池維護線程的最小數量,哪怕是空閒的
12. private volatile int maximumPoolSize; // 線程池維護的最大線程數量
public interface ThreadFactory { Thread newThread(Runnable r); }