中斷可以理解為線(xiàn)程的一個(gè)標(biāo)識(shí)位屬性,
它表示一個(gè)運(yùn)行中的線(xiàn)程是否被其他線(xiàn)程進(jìn)行了中斷。
中斷只是通知一下該線(xiàn)程,但是不強(qiáng)制停止。如果響應(yīng)中斷時(shí)不做處理,該線(xiàn)程還是會(huì)繼續(xù)運(yùn)行下去的。
中斷好比其他線(xiàn)程給該線(xiàn)程打了個(gè)招呼
調(diào)用該線(xiàn)程的interrupt()方法
該線(xiàn)程可以判斷自己是否被中斷線(xiàn)程內(nèi)部調(diào)用isInterrupted()方法,被中斷返回true
該線(xiàn)程可以對(duì)中斷標(biāo)識(shí)位進(jìn)行復(fù)位線(xiàn)程內(nèi)部調(diào)用靜態(tài)方法Thread.interrupted()方法
public class Interruped {
public static void main(String[] args) throws InterruptedException {
Thread runner = new Thread(new Runner(),"thread01");
runner.start();
// 讓該線(xiàn)程充分運(yùn)行
TimeUnit.SECONDS.sleep(5);
// 通知該線(xiàn)程可以停止了
runner.interrupt();
}
static class Runner implements Runnable{
@Override
public void run(){
while(true){
// 通過(guò)isInterrupted()判斷當(dāng)前線(xiàn)程是否被中斷
if (Thread.currentThread().isInterrupted()) {
System.out.println(Thread.currentThread().getName() + ": 被中斷了");
// 對(duì)中斷標(biāo)識(shí)位進(jìn)行復(fù)位
Thread.interrupted();
}
}
}
}
}
在拋出InterruptException之前,虛擬機(jī)會(huì)將該線(xiàn)程的中斷標(biāo)識(shí)位清除。此時(shí)如果調(diào)用isInterrupt()方法會(huì)返回false。
public class Interruped {
public static void main(String[] args) throws InterruptedException {
Thread sleepRunner = new Thread(new SleepRunner(),"sleepThread");
Thread busyRunner = new Thread(new BusyRunner(),"busyThread");
sleepRunner.start();
busyRunner.start();
// 這個(gè)很重要,要先讓線(xiàn)程跑起來(lái)
TimeUnit.SECONDS.sleep(5);
sleepRunner.interrupt();
busyRunner.interrupt();
System.out.println("sleepThread is" + sleepRunner.isInterrupted());
System.out.println("busyThread is" + busyRunner.isInterrupted());
}
// 該類(lèi)拋出中斷異常
static class SleepRunner implements Runnable{
@Override
public void run() {
while(true){
try {
Thread.sleep(10*1000);
} catch (InterruptedException e) {
}
}
}
}
// 該類(lèi)不拋出異常
static class BusyRunner implements Runnable{
@Override
public void run() {
while(true){
}
}
}
}
sleepThread is false // 拋出異常的線(xiàn)程中斷標(biāo)識(shí)位被清除
busyThread is true // 沒(méi)有拋出異常的線(xiàn)程沒(méi)有被清除