如何安全的停止一个线程
調用stop方法
Stop:中止線程,并且清除監控器鎖的信息,但是可能導致 線程安全問題,JDK不建議用。 Destroy: JDK未實現該方法。
Interrupt(線程中止)
Interrupt 打斷正在運行或者正在阻塞的線程。
1.如果目標線程在調用Object class的wait()、wait(long)或wait(long, int)方法、join()、join(long, int)或sleep(long, int)方法時被阻塞,那么Interrupt會生效,該線程的中斷狀態將被清除,拋出InterruptedException異常。
2.如果目標線程是被I/O或者NIO中的Channel所阻塞,同樣,I/O操作會被中斷或者返回特殊異常值。達到終止線程的目的。
如果以上條件都不滿足,則會設置此線程的中斷狀態。
打斷正在阻塞的線程
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
try {
Thread.sleep(5000);
} catch (Exception e) {
e.printStackTrace();
}
}, “t1”);
t1.start();
try {
Thread.sleep(1000);
} catch (Exception e) {
}
打斷正在運行的線程
public class Thread06 extends Thread {
@Override
public void run() {
while (true) {
// 如果終止了線程,則停止當前線程
if (this.isInterrupted()) {
break;
}
}
}
}
總結
以上是生活随笔為你收集整理的如何安全的停止一个线程的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: sleep防止CPU占用100%
- 下一篇: 正确的线程中止-标志位