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) { } }
DiscardOldestPolicy
DiscardOldestPolicy将会丢弃最老的任务,保存最新插入的任务。
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); } } }
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(); } } }