本文主要是介绍Code Fragment-提供相对安全和相对粗暴的两种接口胜过单一的接口,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
提供相对安全和相对粗暴的两种接口胜过单一的接口
类
java.util.concurrent.ThreadPoolExecutor
方法
-
shutdown
- 在终止前允许执行以前提交的任务。
- code
/*** Initiates an orderly shutdown in which previously submitted* tasks are executed, but no new tasks will be accepted.* Invocation has no additional effect if already shut down.** <p>This method does not wait for previously submitted tasks to* complete execution. Use {@link #awaitTermination awaitTermination}* to do that.** @throws SecurityException {@inheritDoc} */ public void shutdown() {final ReentrantLock mainLock = this.mainLock;mainLock.lock();try {checkShutdownAccess();advanceRunState(SHUTDOWN);interruptIdleWorkers();onShutdown(); // hook for ScheduledThreadPoolExecutor} finally {mainLock.unlock();}tryTerminate(); }
- shutdownNow
- 阻止正在等待的任务启动,并试图停止正在执行的任务。(相对粗暴)
- code
/*** Attempts to stop all actively executing tasks, halts the* processing of waiting tasks, and returns a list of the tasks* that were awaiting execution. These tasks are drained (removed)* from the task queue upon return from this method.** <p>This method does not wait for actively executing tasks to* terminate. Use {@link #awaitTermination awaitTermination} to* do that.** <p>There are no guarantees beyond best-effort attempts to stop* processing actively executing tasks. This implementation* cancels tasks via {@link Thread#interrupt}, so any task that* fails to respond to interrupts may never terminate.** @throws SecurityException {@inheritDoc}*/ public List<Runnable> shutdownNow() {List<Runnable> tasks;final ReentrantLock mainLock = this.mainLock;mainLock.lock();try {checkShutdownAccess();advanceRunState(STOP);interruptWorkers();tasks = drainQueue();} finally {mainLock.unlock();}tryTerminate();return tasks; }
这篇关于Code Fragment-提供相对安全和相对粗暴的两种接口胜过单一的接口的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!