JAVA線程狀態、線程START方法源碼、多線程、JAVA線程池、如何停止一個線程等多線程問題
這兩個方法有點容易記混,這里就記錄一下源碼。
Thread.interrupted()和Thread.currentThread().isInterrupted()區別
靜態方法Thread.interrupted()源碼如下:
public static boolean interrupted() { return currentThread().isInterrupted(true); }
可以看到,靜態方法內部,調用了currentThread()獲取當前線程后調用非靜態方法isInterrupted();
根據源碼,看到的區別是在於給isInterrupted()方法傳參為true或不傳參。
非靜態方法Thread.currentThread().isInterrupted()源碼如下:
public boolean isInterrupted() {
return isInterrupted(false);
}
調用了isInterrupted(boolean ClearInterrupted)的有參方法:
/** * Tests if some Thread has been interrupted. The interrupted state * is reset or not based on the value of ClearInterrupted that is * passed. */ private native boolean isInterrupted(boolean ClearInterrupted);
該方法先獲取線程中斷狀態,然后在根據參數決定是否重置中斷狀態,true重置,false不重置。
簡單總結下:
靜態方法Thread.interrupted()獲取線程中斷狀態后,會重置中斷狀態為false;
非靜態方法Thread.currentThread().isInterrupted()獲取線程中斷狀態后,不會重置中斷狀態。
