Java 多執行緒 interrupt 中斷

2021-07-24 09:58:34 字數 2507 閱讀 2501

當乙個執行緒執行時,另乙個執行緒可以呼叫對應的thread物件的interrupt()方法來中斷它,該方法只是在目標執行緒中設定乙個標誌,表示它已經被中斷,並立即返回。這裡需要注意的是,如果只是單純的呼叫interrupt()方法,執行緒並沒有實際被中斷,會繼續往下執行。

/**

* created by yangtianrui on 16-11-1.

* #使用interrupt()中斷執行緒:

* * 當乙個執行緒執行時,另乙個執行緒可以呼叫對應的thread物件的interrupt()方法來中斷它,

* 該方法只是在目標執行緒中設定乙個標誌,表示它已經被中斷,並立即返回。這裡需要注意的是,

* 如果只是單純的呼叫interrupt()方法,執行緒並沒有實際被中斷,會繼續往下執行。

* */

public

class

interrupttest catch (interruptedexception e)

thread.interrupt(); // 此處會將子執行緒的休眠中斷, 此中斷會引發interruptexception, 表示終端

system.out.println("main exiting");

}}class subthread implements runnable catch (interruptedexception e)

// 繼續執行

system.out.println("haha");

}}// output:

// main exiting

// thread-0 subthread >> sleep 50 seconds.

// thread-0 handle interruptedexception

// haha

可以在thread物件上呼叫isinterrupted()方法來檢查任何執行緒的中斷狀態。這裡需要注意:執行緒一旦被中斷,isinterrupted()方法便會返回true,而一旦sleep()方法丟擲異常,它將清空中斷標誌,此時isinterrupted()方法將返回false。

public

class

interruptcheck

extends

objectcatch( interruptedexception x)

//丟擲異常後,會清除中斷標誌,這裡會返回false

system.out.println("point d: t.isinterrupted()=" + t.isinterrupted());

} } //isinterrupt=false

//isinterrupt=true

//isinterrupt=false

可以使用thread.interrupted()方法來檢查當前執行緒的中斷狀態(並隱式重置為false)。又由於它是靜態方法,因此不能在特定的執行緒上使用,而只能報告呼叫它的執行緒的中斷狀態,如果執行緒被中斷,而且中斷狀態尚不清楚,那麼,這個方法返回true。與isinterrupted()不同,它將自動重置中斷狀態為false,第二次呼叫thread.interrupted()方法,總是返回false,除非中斷了執行緒。

public

class

interruptreset

extends

object

} //isinterrupt = false

//isinterrupt = true 自動重置標誌位

//isinterrupt = false

在上面的例子中,sleep()方法的實現檢查到休眠執行緒被中斷,它會相當友好地終止執行緒,並丟擲interruptedexception異常。另外一種情況,如果執行緒在呼叫sleep()方法前被中斷,那麼該中斷稱為待決中斷,它會在剛呼叫sleep()方法時,立即丟擲interruptedexception異常。

public

class

pendinginterrupt

extends

object

//獲取當前時間

long starttime = system.currenttimemillis();

trycatch(interruptedexception x)

//計算中間**執行的時間

system.out.println("elapsedtime=" + ( system.currenttimemillis() - starttime));

} }

join方法用執行緒物件呼叫,如果在乙個執行緒a中呼叫另乙個執行緒b的join方法,執行緒a將會等待執行緒b執行完畢後再執行。

yield可以直接用thread類呼叫,yield讓出cpu執行權給同等級的執行緒,如果沒有相同級別的執行緒在等待cpu的執行權,則該執行緒繼續執行。

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...