Java停止线程的方式
生活随笔
收集整理的這篇文章主要介紹了
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停止线程的方式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ubuntu20 隐藏 顶部_ubunt
- 下一篇: python爬虫实例100例-10个py