如何正確的停止一個線程

来源:https://www.cnblogs.com/duodushuduokanbao/archive/2018/08/31/9567433.html
-Advertisement-
Play Games

題外話 複習多線程的知識,偶然看到一道題:如何正確的停止一個線程?我第一反應是使用stop()方法停止,操作以後發現stop已經被廢棄了。 經過查找資料,發現是使用interrupt()進行中斷標記然後在進行停止,特此寫這篇隨筆記錄一下。 stop()、suspend()的缺點 1.會導致一些清理工 ...


================================題外話=================================

複習多線程的知識,偶然看到一道題:如何正確的停止一個線程?我第一反應是使用stop()方法停止,操作以後發現stop已經被廢棄了。

經過查找資料,發現是使用interrupt()進行中斷標記然後在進行停止,特此寫這篇隨筆記錄一下。

------------------------------------------------------------------------------------------------------------------------------------

 

stop()、suspend()的缺點

1.會導致一些清理工作沒有進行,導致一些資源沒有得到回收,導致記憶體泄漏;

2.stop()停止線程會導致對鎖定的對象進行解鎖,在多線程情況下導致數據不一致問題。

 

interrupt()方法

interrupt()方法為為調用該方法的線程對象設置一個中斷標誌,註意!這裡是設置一個中斷標誌,絲毫不耽誤線程沒羞沒臊的運行。請看例子

 1 public class App {
 2     public static void main(String[] args) {
 3 
 4         try {
 5             MyThread thread = new MyThread();
 6             thread.start();
 7             thread.interrupt();
 8             System.out.println("執行了interrupt方法");
 9         } catch (Exception e) {
10             e.printStackTrace();
11         }
12     }
13 
14 }
15 
16 class MyThread extends Thread {
17     
18     public void run() {
19         try{
20             for(int i=0;i<5000;i++){
21                 System.out.println(i);
22             }
23         }catch(Exception e){
24             e.printStackTrace();
25         }
26     }
27 }

運行結果:

1 ....
2 4992
3 4993
4 4994
5 4995
6 4996
7 4997
8 4998
9 4999

說明在調用了interrupt之後,線程並不會停止。

 

使用interrupted()和isInterrupted()判斷中斷狀態

interrupted()作用於調用該方法所在的線程,而不是調用者所在的線程,即無論哪個線程對象調用interrupted()方法,最後結果都是該方法所線上程的狀態結果。

isInterrupted()作用於調用該方法的線程,即誰調用顯示誰的中斷狀態。

並且interrupted()在第二次調用的時候,會恢複線程的狀態,即第一次調用如果是中斷狀態,第二次調用將恢復為非中斷狀態。

isInterruted()僅僅是查看線程的中斷狀態,並不會改變狀態。請看下麵例子

 1 public class App {
 2     public static void main(String[] args) {
 3 
 4         try {
 5             MyThread thread = new MyThread();
 6             thread.start();
 7             thread.interrupt();
 8             
 9             //顯示的是主線程的中斷狀態,所以顯示false
10             System.out.println("調用interrupted():  " + thread.interrupted());
11             
12             //main主線程調用interrupt(),是主線程狀態為中斷
13             Thread.currentThread().interrupt();
14             
15             //這裡也可以使用Thread.currentThread().interrupted(),效果是一樣的,具體原因看上面介紹
16             System.out.println("第一次調用interrupted():  " + thread.interrupted());
17             //第二次調用,interrupted()方法又將狀態恢復
18             System.out.println("第二次調用interrupted():  " + thread.interrupted());
19             
20             System.out.println("-------------------------------------------------");
21             
22             //而isInterrupted()返回的是調用者線程的中斷狀態,而且多次調用狀態不會恢復
23             System.out.println("第一次調用isInterrupted():  " + thread.isInterrupted());
24             System.out.println("第二次調用isInterrupted():  " + thread.isInterrupted());
25         } catch (Exception e) {
26             e.printStackTrace();
27         }
28     }
29 }
30 
31 class MyThread extends Thread {
32     
33     public void run() {
34         try{
35             while(true){
36                 
37             }
38         }catch(Exception e){
39             e.printStackTrace();
40         }
41     }
42 }

運行結果為:

1 調用interrupted():  false
2 第一次調用interrupted():  true
3 第二次調用interrupted():  false
4 -------------------------------------------------
5 第一次調用isInterrupted():  true
6 第二次調用isInterrupted():  true

 

註意:如果線程在睡眠狀態中,線程狀態被修改為interrupted,這是將拋出java.lang.InterruptedException異常,線程將會停止

下麵進入正題,如何正確的停止一個線程

有以下幾個方式:

使用break停止線程:判斷線程狀態為中斷時,使用break跳出run()方法中的迴圈,缺點是雖然跳出了迴圈體,但是迴圈體外的程式還會得到執行,並不能到達立即停止的效果

使用return停止線程:判斷線程狀態為中斷時,使用return退出run()方法

拋出異常停止線程:通過拋出一個異常來停止線程,這是比較推薦的方式

這三種方式實現基本相似,我就拿異常法進行舉例了(偷懶)。

 1 public class App {
 2     public static void main(String[] args) {
 3 
 4         try {
 5             MyThread thread = new MyThread();
 6             
 7             thread.start();
 8             Thread.sleep(2000);
 9             thread.interrupt();
10                         
11             while(true){   //主線程將一直運行
12                 
13             }
14         } catch(Exception e){
15             e.printStackTrace();
16         }
17     }
18 }
19 
20 class MyThread extends Thread {
21     
22     public void run() {
23         try{
24             while(true){
25                 if(isInterrupted()){
26                     throw new InterruptedException();
27                 }
28             }
29         }catch(InterruptedException e){
30             System.out.println("由於異常退出線程");
31             e.printStackTrace();
32         }finally{
33             System.out.println("這是線程的finally");
34         }
35     }
36 }

 

 運行結果:

1 java.lang.InterruptedException
2     at com.sunyong.thread.stop.MyThread.run(App.java:31)
3 由於異常退出線程
4 這是線程的finally

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • Joe works in a maze. Unfortunately, portions of the maze have caught on fire, and the owner of the maze neglected to create a fire escape plan. Help J ...
  • 輸入輸出樣例 輸入樣例#1: 8 186 186 150 200 160 130 197 220 輸出樣例#1: 4 輸入樣例#1: 8 186 186 150 200 160 130 197 220 輸出樣例#1: 4 此題意在先升後降子序列,單調遞增子序列,單調遞減子序列當中找到最長的一組序列。 ...
  • 一丶約束 當我們編寫項目時會創建很多個類,來實現很多個功能,最後又需要把這些類都聯繫成一個,我們就需要來約束一下那些類中的方法,把需要聯繫的約束成一個方法. Email類繼承了BaseMessage,所以Email類中必須有send方法,否則就會報錯,我們用這樣的來約束類 編寫. 示例: class ...
  • 上傳文件的分類: 無論什麼方式上傳文件,都要用post提交方式一: 前端:表單方式上傳文件 <form action="" method="post" enctype="multipart/form-data"> <!--非文件域--> <input type="text" name="desc"/ ...
  • 題意 $n$個食物,每個食物有一個滿意度,從中選出$m$個,使得滿意度最大 同時有$k$個關係:若$x_i$在$y_i$之前吃,則會獲得$C_i$的代價 Sol 官方題解是$O(2^n n^2)$的,不過我沒發現狀態之間的聯繫,就寫了一個$O(2^n n^3)$的,不過還是水過去了。 $f[i][j ...
  • 每天下班回家有時間就寫個小例子,一個月下來的成果,分享給大家學習~ 第一題 1、2、3、4個數字,能組成多少個互不相同且無重覆數字的三位數?都是多少? 程式分析: 可填在百位、十位、個位的數字都是1、2、3、4。組成所有的排列後再去掉不滿足條件的排列。 代碼: 第二題 企業發放的獎金根據利潤提成。利 ...
  • 不同於傳統集中時Springmvc 全局異常,具體查看前面的章節https://www.cnblogs.com/zwdx/p/8963311.html 對於springboot框架來講,這裡我就介紹一種 1、ExceptionHandlerAdvice 由於是前後端分離,所以使用@ResponseB ...
  • JDK中已經內置了Webservice發佈,不過要用Tomcat等Web伺服器發佈WebService,還需要用第三方Webservice框架。Axis2和CXF是目前最流行的Webservice框架,這兩個框架各有優點,不過都屬於重量級框架。 JAX-WS RI是JAX WebService參考實 ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...