Java中斷執行緒的方式

2021-09-11 18:28:55 字數 1004 閱讀 7903

方式一、stop()方法

目前改方法已被註解@deprecated,因為它是執行緒不安全的操作,呼叫stop方法後,執行緒會立即停止,導致執行緒邏輯有一部分未執行,造成得到不可預期的結果。如下**中,預期輸出的結果是i=j,但是使用stop中斷執行緒後,大概率出現j = i + 1.

public class stopthread extends thread catch (interruptedexception e) 

j++;

} }private static void print()

public static void main(string args) throws interruptedexception

}

方式二:interrupt,執行緒物件呼叫interrupt函式後,相當於新增了乙個標記,執行緒執行的時候使用isinterruptted方法判斷是否有標記,有則中斷執行緒,無則繼續執行

package com.jemmy.stopthread;

public class interruptthread implements runnable

} public static void main(string args) throws interruptedexception

}

方法三:自定義flag,鑑於interrupt的標記原理,可以通過自定義flag的方式來中斷執行緒。volatile修飾flag主要是保證中斷執行緒的及時性。

volatile關鍵字修飾變數,修改變數值時直接修改變數本身的值,而非volatile修飾的變數,先修改該變數的乙個副本,再將副本的值寫入儲存變數的記憶體位址中。

public class diystopthread implements runnable

} public static void main(string args) throws interruptedexception

}

中斷執行緒的方式

變數標識 匿名內部類使用區域性變數時,必須是 final,否則編譯報錯 匿名內部類使用字段,不需要 final 使用 volatile 修飾,實現多執行緒間變數的可見性 volatile boolean loop true while condition test public void testw...

JAVA中斷執行緒的方法

thread.stop,thread.suspend,thread.resume和runtime.runfinalizersonexit這些終止執行緒執行的方法已經被廢棄,使用它們是極端不安全的!現在,如果你要安全有效地終止乙個執行緒,應該採用以下這些方法 1,執行緒正常執行完畢,正常結束。也就是讓...

Java併發(3) 中斷執行緒

2011 03 21 mon comments 在了解如何中斷執行緒之前,先應該弄清楚執行緒的幾種狀態 新建狀態 new 乙個新的執行緒在被建立之後,在執行 或阻塞 之前的狀態。就緒狀態 runnable 當乙個執行緒只要擁有cpu時間片就能執行的時候,這個執行緒就處於就緒狀態。阻塞狀態 block...