1.join()
作用:主线程等待子线程终止
抛出:
InterruptedException - 如果任何线程中断了当前线程。当抛出该异常时,当前线程的中断状态 被清除。
2.interrupt()
@Override
public void run() {
try {
// 1. isInterrupted()保证,只要中断标记为true就终止线程。
while (!isInterrupted()) {
// 执行任务...
}
} catch (InterruptedException ie) {
// 2. InterruptedException异常保证,当InterruptedException异常产生时,线程被终止。
}
}
当对一个线程,调用 interrupt() 时
① 如果线程处于正常活动状态,那么会将该线程的中断标志设置为 true。被设置中断标志的线程将继续正常运行,不受影响。
② 如果线程处于被阻塞状态(sleep, wait, join 等状态),那么线程将立即退出被阻塞状态,并抛出一个InterruptedException