本帖最后由 xu6148152 于 2014-1-13 14:08 编辑
shutDown()
当线程池调用该方法时,线程池的状态则立刻变成SHUTDOWN状态。此时,则不能再往线程池中添加任何任务,否则将会抛出RejectedExecutionException异常。但是,此时线程池不会立刻退出,直到添加到线程池中的任务都已经处理完成,才会退出。- public void shutdown()
- {
- SecurityManager security = System.getSecurityManager();
- if (security != null)
- security.checkPermission(shutdownPerm);
- final ReentrantLock mainLock = this.mainLock;
- mainLock.lock();
- try {
- if (security != null) { // Check if caller can modify our threads
- for (Worker w : workers)
- security.checkAccess(w.thread);
- }
- int state = runState;
- if (state < SHUTDOWN)
- //设置线程池状态为关闭状态
- runState = SHUTDOWN; //----------------代码1
- try {
- for (Worker w : workers) {
- //一个一个中断线程
- w.interruptIfIdle(); //-----------------代码2
- }
- } catch (SecurityException se) { // Try to back out
- runState = state;
- // tryTerminate() here would be a no-op
- throw se;
- }
- tryTerminate(); // Terminate now if pool and queue empty
- } finally {
- mainLock.unlock();
- }
- }
复制代码
shutdownNow()
根据JDK文档描述,大致意思是:执行该方法,线程池的状态立刻变成STOP状态,并试图停止所有正在执行的线程,不再处理还在池队列中等待的任务,当然,它会返回那些未执行的任务。
它试图终止线程的方法是通过调用Thread.interrupt()方法来实现的,但是大家知道,这种方法的作用有限,如果线程中没有sleep 、wait、Condition、定时锁等应用, interrupt()方法是无法中断当前的线程的。所以,ShutdownNow()并不代表线程池就一定立即就能退出,它可能必须要等待所有正在执行的任务都执行完成了才能退出。
- public List<Runnable> shutdownNow()
- {
- /*
- * shutdownNow differs from shutdown only in that
- * 1. runState is set to STOP,
- * 2. all worker threads are interrupted, not just the idle ones, and
- * 3. the queue is drained and returned.
- */
- SecurityManager security = System.getSecurityManager();
- if (security != null)
- security.checkPermission(shutdownPerm);
-
- final ReentrantLock mainLock = this.mainLock;
- mainLock.lock();
- try {
- if (security != null) { // Check if caller can modify our threads
- for (Worker w : workers)
- security.checkAccess(w.thread);
- }
-
- int state = runState;
- if (state < STOP)
- runState = STOP;
-
- try {
- for (Worker w : workers) {
- w.interruptNow();
- }
- } catch (SecurityException se) { // Try to back out
- runState = state;
- // tryTerminate() here would be a no-op
- throw se;
- }
-
- List<Runnable> tasks = drainQueue();
- tryTerminate(); // Terminate now if pool and queue empty
- return tasks;
- } finally {
- mainLock.unlock();
- }
- }
复制代码
|