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); }