shutdownNow关不掉线程

@Override
public void run() {

    try {
        while (!Thread.interrupted()) {
            while (!car.waxOn) {
                car.waxOn();
            }
        }
    } catch (InterruptedException e) {
        System.out.println("waxon interrupted");
    }

}

@Override
public void run() {
    while (!Thread.interrupted()) {
        while (!car.waxOn) {
            try {

                car.waxOn();

            } catch (InterruptedException e) {
                System.out.println("waxon interrupted");
            }
        }
    }
}

上下两个run方法比较,while (!Thread.interrupted()) 判断应该放在try代码快里。否则像下面的写法,catch会吞掉InterruptedException,到时判断检测不出来以至于shutdownNow关不掉线程

shutdownNow的原理是为每个线程调用 interruput方法,然后有run方法里的判断语句来检查Thread.interrupted()

你可能感兴趣的:(线程)