日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

Java停止线程的方式

發布時間:2023/12/10 java 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Java停止线程的方式 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

?


1、使用中斷標志位

public class StopThreadTest extends Thread {private boolean exit = false;@Overridepublic void run() {while (!exit) {try {System.out.println("i am running,please wait a moment");Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}}}public static void main(String[] args) {try {StopThreadTest threadTest = new StopThreadTest();threadTest.start();Thread.sleep(4000);threadTest.exit = true;} catch (InterruptedException e) {e.printStackTrace();}} }

2、?使用 interrupt() 中斷線程

嚴格的說,線程中斷并不會使線程立即退出,而是給線程發送一個通知,告知目標線程,有人希望你退出了!至于目標線程接收到通知之后如何處理,則完全由目標線程自己決定

線程阻塞狀態中如何中斷?

public class StopThreadTest{public static void main(String[] args) throws InterruptedException {Thread thread = new Thread() {@Overridepublic void run() {while (true){System.out.println("i am running");try {TimeUnit.SECONDS.sleep(100);} catch (InterruptedException e) { // this.interrupt();e.printStackTrace();}if (Thread.currentThread().isInterrupted()){System.out.println("i am exit");break;}}}};thread.start();TimeUnit.SECONDS.sleep(1);thread.interrupt();} }

運行上面的代碼,發現程序無法終止

sleep方法由于中斷而拋出異常之后,線程的中斷標志會被清除(置為false),所以在異常中需要執行this.interrupt()方法,將中斷標志位置為true

public class StopThreadTest{public static void main(String[] args) throws InterruptedException {Thread thread = new Thread() {@Overridepublic void run() {while (true){System.out.println("i am running");try {TimeUnit.SECONDS.sleep(100);} catch (InterruptedException e) {this.interrupt();e.printStackTrace();}if (Thread.currentThread().isInterrupted()){System.out.println("i am exit");break;}}}};thread.start();TimeUnit.SECONDS.sleep(1);thread.interrupt();} }
  • 調用線程的interrupt()實例方法,線程的中斷標志會被置為true

  • 當線程處于阻塞狀態時,調用線程的interrupt()實例方法,線程內部會觸發InterruptedException異常,并且會清除線程內部的中斷標志(即將中斷標志置為false)

    public class StopThreadTest {/*** 通過interrupt()方式進行中斷,同時運用了volatile,保證了flag變量在主線程與T1線程可見性*/public volatile static boolean flag = true;public static class T1 extends Thread {public T1(String name) {super(name);}@Overridepublic void run() {System.out.println("線程 " + this.getName() + " in");while (flag) {}System.out.println("線程 " + this.getName() + " stop");}}public static void main(String[] args) throws InterruptedException {T1 cp = new T1("cp");cp.start();TimeUnit.SECONDS.sleep(1);flag = false;} }

    ?

  • 總結

    以上是生活随笔為你收集整理的Java停止线程的方式的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。