线程池ThreadPoolExecutor相关自整理

ThreadPoolExecutor 相关整理

为什么 使用 shutDown方法,线程并不会关闭;

原因:执行 shutDown方法只会去尝试执行中断线程,但是中断是有条件的

  1. 当前任务线程没有被中断
  2. 当前线程处于空闲状态;

ThreadPoolExecutor#shutdown具体代码逻辑

1. shutDown方法
public void shutdown() {
        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            checkShutdownAccess();
            advanceRunState(SHUTDOWN);
            // 中断空闲的线程任务;如果当前线程有任务则不予执行
            interruptIdleWorkers();
            // 回调通知方法;默认为空
            onShutdown(); // hook for ScheduledThreadPoolExecutor
        } finally {
            mainLock.unlock();
        }
    	// 尝试终止;由于线程并没有被中断;依旧会执行上面的interruptIdleWorkers()方法,因为还有任务依旧无法中断
        tryTerminate();
    }
2. ThreadPoolExecutor#interruptIdleWorkers 方法会执行 interruptIdleWorkers方法
// 中断 没有任务可做的workers
private void interruptIdleWorkers(boolean onlyOne) {
        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            for (Worker w : workers) {
                Thread t = w.thread;
                // 如果当前线程不是被中断并且当前线程处于空闲状态
                // w.tryLock() 返回false 所以不会执行 t.interrupt();
                if (!t.isInterrupted() && w.tryLock()) {
                    try {
                        t.interrupt();
                    } catch (SecurityException ignore) {
                    } finally {
                        w.unlock();
                    }
                }
                if (onlyOne)
                    break;
            }
        } finally {
            mainLock.unlock();
        }
    }
3. ThreadPoolExecutor.Worker#tryLock
public boolean tryLock()  { return tryAcquire(1); }  
//实际执行尝试加锁逻辑
protected boolean tryAcquire(int unused) {
      		// 会设置失败;因为线程此时正在执行任务,已被修改预期值为1了
            if (compareAndSetState(0, 1)) {
                setExclusiveOwnerThread(Thread.currentThread());
                return true;
            }
            return false;
        }

上面操作尝试修改当前Worker的状态从 0–> 1 ,由于当前线程正在执行任务中,所以结果返回false;因为当任务提交启动线程执行的时候,会执行 一次lock,会修改Worker状态预期值从 0 --> 1;直到当前任务执行结束才会释放锁,具体代码逻辑

4. ThreadPoolExecutor#runWorker
// 线程池提交任务,核心线程在执行的时候会执行此方法;设置lock锁
final void runWorker(Worker w) {
        Thread wt = Thread.currentThread();
        Runnable task = w.firstTask;
        w.firstTask = null;
        w.unlock(); // allow interrupts
        boolean completedAbruptly = true;
        try {
            while (task != null || (task = getTask()) != null) {
                // 此处会执行加锁逻辑; 会修改值为1 
                w.lock();
                // If pool is stopping, ensure thread is interrupted;
                // if not, ensure thread is not interrupted.  This
                // requires a recheck in second case to deal with
                // shutdownNow race while clearing interrupt
                if ((runStateAtLeast(ctl.get(), STOP) ||
                     (Thread.interrupted() &&
                      runStateAtLeast(ctl.get(), STOP))) &&
                    !wt.isInterrupted())
                    wt.interrupt();
                try {
                    beforeExecute(wt, task);
                    Throwable thrown = null;
                    try {
                        // 线程执行具体任务;
                        task.run();
                    } catch (RuntimeException x) {
                        thrown = x; throw x;
                    } catch (Error x) {
                        thrown = x; throw x;
                    } catch (Throwable x) {
                        thrown = x; throw new Error(x);
                    } finally {
                        afterExecute(task, thrown);
                    }
                } finally {
                    task = null;
                    w.completedTasks++;
                    // 任务执行结束释放锁;修改状态为0
                    w.unlock();
                }
            }
            completedAbruptly = false;
        } finally {
            processWorkerExit(w, completedAbruptly);
        }
    }

为什么使用shutDownNow方法会立即关闭线程;

原因 :在执行shutDownNow 中断的条件:

  1. 会判断当前woker状态 >= 0 ;
  2. 当前的执行线程并没有被打断;

ThreadPoolExecutor#shutdowNow具体逻辑

1. shutdownNow 方法
 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;
    }
2. ThreadPoolExecutor#interruptWorkers
 private void interruptWorkers() {
        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            for (Worker w : workers)
                //中断已开启的线程
                w.interruptIfStarted();
        } finally {
            mainLock.unlock();
        }
    }
3. ThreadPoolExecutor.Worker#interruptIfStarted
 void interruptIfStarted() {
            Thread t;
     // 此处的判断条件很简单;并不会判断当前worker是否在执行中
            if (getState() >= 0 && (t = thread) != null && !t.isInterrupted()) {
                try {
                    t.interrupt();
                } catch (SecurityException ignore) {
                }
            }
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值