Java多執行緒 interrupt中斷阻塞

2021-09-11 03:22:04 字數 2122 閱讀 7169

——interrupt()方法並不是中斷執行緒,而是中斷阻塞狀態,或者將執行緒的[中斷標誌位]置為true。

——對於未阻塞的執行緒,interrupt()只是造成[中斷標誌位]=true,執行緒本身執行狀態不受影響。

——對於阻塞的執行緒,interrupt()會中斷阻塞狀態,使其轉換成非阻塞狀態,並清除[中斷標誌位]。

——造成阻塞狀態的情況有:sleep()、wait()和join()。

——阻塞狀態的執行緒被中斷時,只是中斷了阻塞狀態,即sleep()、wait()和join(),執行緒本身還在繼續執行。

例項演示

1 非阻塞執行緒呼叫interrupt()方法    只是將中斷標誌位設定為true 不會影響執行緒正常執行

public class interruptedemo 

}logger.info("執行緒"+thread.getname()+"停止執行"+"isinterrupted="+thread.isinterrupted());

2 通過interrupt()與isinterrupted()控制for迴圈的執行狀態(非阻塞執行緒)  即根據中斷標誌位 進行控制

new thread(

()->

}logger.info("執行緒"+thread.getname()+"停止執行"+"isinterrupted="+thread.isinterrupted());

}).start();

可以看到執行到i=2之後不在執行 

3  阻塞執行緒(sleep/wait/joni)中的while迴圈應用interrupt()和isinterrupted()

system.out.println();

logger.info("在有阻塞狀態(sleep/wait/joni)的while迴圈中應用interrupt()和isinterrupted()");

thread thread2 = new thread(() -> catch (interruptedexception e)

}logger.info("執行緒[" + thread.currentthread().getname() + "]停止執行");

建立了thread2執行run後 由於sleep睡眠5秒 進入阻塞態

而主線程呼叫 thread2.interrupt將修改thread2的中斷位 

使得還在5秒鐘睡眠時間內的執行緒被打斷 丟擲異常

但是程式還是會繼續執行

由此可以發現這種方式 並不能跳出迴圈 不是想要的結果

解決方案: 將catch塊外移動

可以看到成功的在呼叫interrupt之後結束迴圈

由此可見對阻塞執行緒的控制一般方法

@override

public void run()catch(interruptedexception e)

}thread.interrupt();

java多執行緒

在網上看到很有意思的問題,摘下來好好看下 在面試的時候被問了乙個多執行緒的問題 回來仔細思考了一下,多執行緒是否真的能提高了效率?我對多執行緒的理解就是 比如挖乙個隧道,有2種開工方法 1 只在山的一頭挖,直至挖到山的另一頭,從而打通隧道,這可以看成是單執行緒 2 在山的兩頭挖,同時開工,最後在山的...

Java 多執行緒

1。thread類和runnable介面 2。主線程 用thread的static thread currentthread 方法獲得 3。通過實現runnable介面建立執行緒 實現runnable介面的run方法。新執行緒在run 方法返回時結束。注意用這種方法建立程序時,在實現runnable...

JAVA 多執行緒

為hashmap的不正確使用所導致。hashmap在多執行緒環境下使用不安全。使用靜態hashmap作為聯絡人資料快取,key為手機號碼.private static maplxrdata new hashmap 多執行緒環境下不同步hashmap可能導致如下問題 1 多執行緒put操作後可能導致g...