java多線程學習之停止休眠中的線程問題

package learn.thread;

/*

 * 線程停止方法方法 -使休眠中的線程進入停止狀態
 * 報這個錯,然後停止線程java.lang.InterruptedException: sleep interrupted
 * 如果先設置停止狀態後再休眠,會休眠後在退出
 */
public class Demo7 extends Thread {
    public Demo7(String name) {
        super(name);
    }

    String name;

    @Override
    public void run() {
//      for (int i = 0; i < 500000; i++) {
//          System.out.println("i: " + (i + 1));
//      }
        try {
            Thread.sleep(20000);
            System.out.println("我是他後面的代碼,表示線程沒有立即停止");
        } catch (InterruptedException e) {
            System.err.println("進入run的catch");
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Demo7 t1 = new Demo7("A");
        t1.start();
        try {
            Thread.sleep(1000);
            System.out.println("線程是否中止狀態: " + t1.isInterrupted());
            // 標記線程中斷方法
            t1.interrupt();
            System.out.println("線程是否中止狀態: " + t1.isInterrupted());

        } catch (InterruptedException e) {
            System.out.println("進入catch");
            e.printStackTrace();
        }
        System.out.println("end");
    }

}
發佈了49 篇原創文章 · 獲贊 4 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章