interrupt —— 當(dāng)其他線程通過調(diào)用當(dāng)前線程的interrupt方法,表示向當(dāng)前線程打個(gè)招呼,告訴他可以中斷線程的執(zhí)行了,至于什么時(shí)候中斷,取決于當(dāng)前線程自己
@Slf4j
public class InterruptDemo {
private static int i;
// while 情況下 interrupt 執(zhí)行有意義
//線程處于阻塞狀態(tài)下的情況下(中斷才有意義)
// 阻塞狀態(tài): thread.join wait thread.sleep (從阻塞中喚醒拋出一個(gè)異常來中斷線程)
public static void main(String[] args) {
Thread thread = new Thread(()->{
//Thread.currentThread().isInterrupted() 默認(rèn)是false
//判斷中斷標(biāo)識
while (!Thread.currentThread().isInterrupted()){
log.info("I: "+i);
i++;
log.info("I: "+i);
}
});
thread.start();
thread.interrupt();//中斷(友好)
}
}
Thread.interrupted() 對設(shè)置中斷標(biāo)識的線程復(fù)位,并且返回當(dāng)前的中斷狀態(tài)
/**
* Thread.interrupted(); 對設(shè)置中斷標(biāo)識的線程復(fù)位,并且返回當(dāng)前的中斷狀態(tài)
* @throws InterruptedException
*/
public void exp3() throws InterruptedException {
Thread thread = new Thread(()->{
while (true){
if (Thread.currentThread().isInterrupted()){
log.info("------"+Thread.currentThread().isInterrupted());
Thread.interrupted();
log.info("-======+=="+Thread.currentThread().isInterrupted());
}
}
});
thread.start();
TimeUnit.SECONDS.sleep(11);
thread.interrupt();
}
簡單的理解就是 thread.interrupt();和Thread.interrupted(); 這兩個(gè)就是一個(gè)線程的開關(guān), thread.interrupt()就是將一個(gè)線程關(guān)閉,而Thread.interrupted()就是將受到thread.interrupt()作用的線程給打開阻止其關(guān)閉。