轉自:
http://www.java265.com/JavaCourse/202204/3189.html
在java中我們引入中斷的目的是為了打斷執行緒現在所處的某種狀態,但是我們知道這種狀態一定是阻塞狀態;
在執行緒阻塞的時候,我們想要改變它阻塞的狀態,所以通常在執行緒sleep,wait,join的情況下我們可以使用中斷;
由于中斷可以捕獲,通過這種方式我們可以結束執行緒;
中斷不是結束執行緒,只不過發送了一個中斷信號而已,執行緒要退出還要我們加上自己的結束執行緒的操作,
下文筆者講述使用Java代碼中斷執行緒的方法分享,如下所示:
實作思路: 使用interrupt()方法進行執行緒中斷
在中斷前,我們可使用isInterrupted()方法,判斷一下執行緒是否已中斷
package com.java265.other; public class Test16 { public static void main(String[] args) throws Exception { MyThread2 a = new MyThread2(); // 啟動執行緒 a.start(); try { Thread.sleep(2000); } catch (InterruptedException x) { } System.out.println("in main() - 中斷其他執行緒"); a.interrupt(); System.out.println("in main() - 離開"); } } class MyThread2 extends Thread { public void run() { try { System.out.println("in run() - 將運行 work() 方法"); work(); System.out.println("in run() - 從 work() 方法回來"); } catch (InterruptedException x) { System.out.println("in run() - 中斷 work() 方法"); return; } System.out.println("in run() - 休眠后執行"); System.out.println("in run() - 正常離開"); } public void work() throws InterruptedException { while (true) { if (Thread.currentThread().isInterrupted()) { System.out.println("C isInterrupted()=" + Thread.currentThread().isInterrupted()); Thread.sleep(2000); System.out.println("D isInterrupted()=" + Thread.currentThread().isInterrupted()); } } } } -----運行以上代碼,將輸出以下資訊----- in run() - 將運行 work() 方法 in main() - 中斷其他執行緒 in main() - 離開 C isInterrupted()=true in run() - 中斷 work() 方法
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/467926.html
標籤:Java
