優雅的執行緒中止

2021-10-03 12:51:54 字數 1142 閱讀 7907

stop:中止執行緒,並清除監控器鎖的資訊,但是可能導致執行緒安全問題,jdk不建議使用

執行緒安全問題:當子執行緒未執行完時在主線程使用stop終止了子執行緒會導致執行緒安全問題

**示例:

package com.hzw;

public

class

demo2

thread.

print()

;}}

package com.hzw;

public

class

stopthread

extends

thread

catch

(interruptedexception e)

++j;}}

public

void

print()

}

做了什麼事

總結:interrupt方法會向執行緒中發出乙個打斷訊號,當訊號遇到執行緒中的阻塞方法時會打斷阻塞,如果沒有遇到阻塞方法則會「軟打斷」執行緒(不直接打斷執行緒,只是將執行緒中斷狀態改為true)

如何終止執行緒

package com.hzw.subject1.video;

public class demo7 catch (interruptedexception e) }}

};testthread.start();

thread.sleep(10000);

testthread.interrupt();

}}

增加乙個判斷,用來控制線程的中止

package com.hzw;

public

class

demo3

catch

(interruptedexception e)}}

}).start()

; thread.

sleep

(3000l)

; flag =

false

; system.out.

println

("程式執行結束");

}}

golang中的優雅中止

不過,業務中 總會存在對中止比較敏感的介面 比如支付相關 並且 總會存在一些帶狀態的服務,此時優雅中止就顯得比較重要了。本文通過乙個go 定時任務示例來簡單介紹 go 技術棧中優雅中止的處理思路。作為高可靠的服務平台,k8s 定義了終止 pod 業務程序在 pod 中執行 的基本步驟 當主動刪除 p...

執行緒中止方式

stop stop方式已被棄用,它會強行中斷程式的執行,導致執行緒安全問題 public class demo3 輸出結果 thread.print public class stopthread extends thread catch interruptedexception e j publi...

多執行緒之執行緒的中止

1 安全中止執行緒 安全中止執行緒有以下兩種方法 1.1 執行緒函式返回 直接使用return語句。1.2 呼叫afxendthread函式 函式定義如下 void afxendthread uint nexitcode 引數nexitcode為執行緒的退出碼。執行緒0 setevent m pth...