java 強制中斷線程運行

lope 9年前發布 | 2K 次閱讀 Java

public class Test implements Runnable {
    public void run() {
        try {
            System.out.println("在run()方法中 - 這個線程會運行20秒");
            Thread.sleep(20000);
            System.out.println("在run()方法中 - 繼續運行");
        } catch (InterruptedException x) {
            System.out.println("在run()方法中 - 中斷線程"); // 捕捉到中斷異常,立即停止運行
            return;
        }
        System.out.println("在run()方法中 - 休眠之后繼續完成");
        System.out.println("在run()方法中 - 正常退出");
    }

public static void main(String[] args) {
    Test si = new Test();
    Thread t = new Thread(si);
    t.start();
    // 在此休眠是為確保線程能運行一會
    try {
        Thread.sleep(2000);
    } catch (InterruptedException x) {
    }
    System.out.println("在main()方法中 - 中斷其它線程");
    t.interrupt(); // 實際上t線程要運行20秒,但是在主線程中2秒后就終止了t線程
    System.out.println("在main()方法中 - 退出");
}

} </pre>

 本文由用戶 lope 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!