java中如何停止一個正在運行的線程
如何停止一個正在運行的線程
1)設置標志位
如果線程的run方法中執(zhí)行的是一個重復執(zhí)行的循環(huán),可以提供一個標記來控制循環(huán)是否繼續(xù)
代碼示例:
public class FunDemo02 { /** * 練習2:設計一個線程:運行10秒后被終止(掌握線程的終止方法) * @param args */ public static void main(String[] args) throws Exception{ MyRunable02 runnable = new MyRunable02(); new Thread(runnable).start(); Thread.sleep(10000); // 主線程休眠10秒鐘 runnable.flag = false; System.out.println("main、 end ..."); } } class MyRunable02 implements Runnable{ boolean flag = true; @Override public void run() { while(flag){ try { Thread.sleep(1000); System.out.println(new Date()); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(Thread.currentThread().getName() + " 執(zhí)行完成"); } }
2)利用中斷標志位
在線程中有個中斷的標志位,默認是false,當我們顯示的調用 interrupted方法或者isInterrupted方法是會修改標志位為true。
我們可以利用此來中斷運行的線程。
代碼示例:
package com.bobo.fundemo; public class FunDemo07 extends Thread{ public static void main(String[] args) throws InterruptedException { Thread t1 = new FunDemo07(); t1.start(); Thread.sleep(3000); t1.interrupt(); // 中斷線程 將中斷標志由false修改為了true // t1.stop(); // 直接就把線程給kill掉了 System.out.println("main .... "); } @Override public void run() { System.out.println(this.getName() + " start..."); int i = 0 ; // Thread.interrupted() 如果沒有被中斷 那么是false 如果顯示的執(zhí)行了interrupt 方法就會修改為 true while(!Thread.interrupted()){ System.out.println(this.getName() + " " + i); i++; } System.out.println(this.getName()+ " end .... "); } }
3)利用InterruptedException異常
如果線程因為執(zhí)行join(),sleep()或者wait()而進入阻塞狀態(tài),此時要想停止它,可以讓他調用interrupt(),程序會拋出InterruptedException異常。
我們利用這個異??梢詠斫K止線程。
package com.bobo; public class FunDemo08 extends Thread{ public static void main(String[] args) throws InterruptedException { Thread t1 = new FunDemo08(); t1.start(); Thread.sleep(3000); t1.interrupt(); // 中斷線程 將中斷標志由false修改為了true // t1.stop(); // 直接就把線程給kill掉了 System.out.println("main .... "); } @Override public void run() { System.out.println(this.getName() + " start..."); int i = 0 ; // Thread.interrupted() 如果沒有被中斷 那么是false 如果顯示的執(zhí)行了interrupt 方法就會修改為 true while(!Thread.interrupted()){ //while(!Thread.currentThread().isInterrupted()){ try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); break; } System.out.println(this.getName() + " " + i); i++; } System.out.println(this.getName()+ " end .... "); } }
總結
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Lombok 的@StandardException注解解析
@StandardException 是一個實驗性的注解,添加到 Project Lombok 的 v__1.18.22 版本中,在本教程中,我們將使用 Lombok 的 @StandardException 注解自動生成異常類型類的構造函數(shù),需要的朋友可以參考下2023-05-05Java使用Lua實現(xiàn)動態(tài)擴展和腳本自動升級
Lua是一種輕量級的腳本語言,常用于游戲開發(fā)和嵌入式系統(tǒng)中,這篇文章主要介紹了Java如何調用Lua實現(xiàn)動態(tài)擴展和腳本自動升級,感興趣的可以學習下2023-08-08Java利用Redis實現(xiàn)高并發(fā)計數(shù)器的示例代碼
這篇文章主要介紹了Java利用Redis實現(xiàn)高并發(fā)計數(shù)器的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-02-02