ExecutorService threadPool = new ThreadPoolExecutor( 2, 5, 3, TimeUnit.SECONDS, new LinkedBlockingDeque<>(3), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
publicstaticclassAbortPolicyimplementsRejectedExecutionHandler{ /** * Creates an {@code AbortPolicy}. */ publicAbortPolicy(){ }
/** * Always throws RejectedExecutionException. * * @param r the runnable task requested to be executed * @param e the executor attempting to execute this task * @throws RejectedExecutionException always */ publicvoidrejectedExecution(Runnable r, ThreadPoolExecutor e){ thrownew RejectedExecutionException("Task " + r.toString() + " rejected from " + e.toString()); } }
超出最大承载会抛出RejectedExecutionException异常
最大承载: Deque + max
CallerRunsPolicy
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
publicstaticclassCallerRunsPolicyimplementsRejectedExecutionHandler{ /** * Creates a {@code CallerRunsPolicy}. */ publicCallerRunsPolicy(){ }
/** * Executes task r in the caller's thread, unless the executor * has been shut down, in which case the task is discarded. * * @param r the runnable task requested to be executed * @param e the executor attempting to execute this task */ publicvoidrejectedExecution(Runnable r, ThreadPoolExecutor e){ if (!e.isShutdown()) { r.run(); } } }
publicstaticclassDiscardOldestPolicyimplementsRejectedExecutionHandler{ /** * Creates a {@code DiscardOldestPolicy} for the given executor. */ publicDiscardOldestPolicy(){ }
/** * Obtains and ignores the next task that the executor * would otherwise execute, if one is immediately available, * and then retries execution of task r, unless the executor * is shut down, in which case task r is instead discarded. * * @param r the runnable task requested to be executed * @param e the executor attempting to execute this task */ publicvoidrejectedExecution(Runnable r, ThreadPoolExecutor e){ if (!e.isShutdown()) { e.getQueue().poll(); e.execute(r); } } }
队列满了,尝试和最早的竞争,也不会抛出异常
DiscardPolicy
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
publicstaticclassDiscardPolicyimplementsRejectedExecutionHandler{ /** * Creates a {@code DiscardPolicy}. */ publicDiscardPolicy(){ }
/** * Does nothing, which has the effect of discarding task r. * * @param r the runnable task requested to be executed * @param e the executor attempting to execute this task */ publicvoidrejectedExecution(Runnable r, ThreadPoolExecutor e){ } }