轉載:https://www.cnblogs.com/jenkov/p/juc_interrupt.html
進階文章(有基礎的可以看看)https://www.cnblogs.com/onlywujun/p/3565082.html
在java的api中有stop、suspend等方法可以停止一個線程,但由於這些方法在使用上存在不安全性,會帶來不好的副作用,不建議被使用。
原因:https://blog.csdn.net/xingjiarong/article/details/47984659
首先明確:中斷不是停止一個線程,只是改變中斷狀態
中斷在java中主要有3個方法,interrupt(),isInterrupted()和interrupted()。
- interrupt(),在一個線程中調用另一個線程的interrupt()方法,即會向那個線程發出信號——線程中斷狀態已被設置。至於那個線程何去何從,由具體的代碼實現決定。
- isInterrupted(),用來判斷當前線程的中斷狀態(true or false)。
- interrupted()是個Thread的static方法,用來恢復中斷狀態
首先一個普通的中斷線程的例子:
public class InterruptionInJava implements Runnable{
private volatile static boolean on = false;
public static void main(String[] args) throws InterruptedException {
Thread testThread = new Thread(new InterruptionInJava(),"InterruptionInJava");
//start thread
testThread.start();
Thread.sleep(1000);
InterruptionInJava.on = true;
System.out.println("main end");
}
@Override
public void run() {
while(!on){
if(Thread.currentThread().isInterrupted()){
System.out.println("Yes,I am interruted,but I am still running");
}else{
System.out.println("not yet interrupted");
}
}
}
}
運行結果:
這種開關的方式看起來包治百病,但是當遇到線程阻塞時,就會很無奈了,正如下面代碼所示:
public class InterruptionInJava implements Runnable{
private volatile static boolean on = false;
public static void main(String[] args) throws InterruptedException {
Thread testThread = new Thread(new InterruptionInJava(),"InterruptionInJava");
//start thread
testThread.start();
Thread.sleep(1000);
InterruptionInJava.on = true;
System.out.println("main end");
}
@Override
public void run() {
while(!on){
try {
Thread.sleep(10000000);
} catch (InterruptedException e) {
System.out.println("caught exception: "+e);
}
}
}
}
線程被阻塞無法被中斷。這時候救世主interrupt函數又回來了,它可以迅速中斷被阻塞的線程,拋出一個InterruptedException,把線程從阻塞狀態中解救出來,show the code。
public class InterruptionInJava implements Runnable{
private volatile static boolean on = false;
public static void main(String[] args) throws InterruptedException {
Thread testThread = new Thread(new InterruptionInJava(),"InterruptionInJava");
//start thread
testThread.start();
Thread.sleep(1000);
InterruptionInJava.on = true;
testThread.interrupt();
System.out.println("main end");
}
@Override
public void run() {
while(!on){
try {
Thread.sleep(10000000);
} catch (InterruptedException e) {
System.out.println("caught exception right now: "+e);
}
}
}
}
運行結果: