java中如何靠interrupt来停止stop一个线程

ii)停止(stop)一个线程(靠interrupt手段) 

下面给出了一个主线程通过interrupt手段,来停止子线程的例子。

例:1.5.2

class ThreadMark_to_win extends Thread {
    public void run() {
        for (int i = 0; i < 100; i++) {
            try {                                   
                Thread.sleep(100);
            } catch (InterruptedException e) {
                System.out.println("我被打断");
                return;
            }
            System.out.println("i = " + i);
        }
    }
}
public class Test {
    public static void main(String[] args) {
        ThreadMark_to_win mt = new ThreadMark_to_win();
        mt.start();
        try {
            Thread.sleep(250);
        } catch (Exception e) {
            e.printStackTrace();
        }
/*mt.interrupt();等于进入到那个线程中,抛出一个InterruptedException异常。当然那个线程的catch能捕获到了*/        
        mt.interrupt();
    }
}

更多内容请见原文,文章转载自:https://blog.csdn.net/qq_44639795/article/details/103099321

posted @ 2021-03-31 08:47  小龙虾1  阅读(69)  评论(0)    收藏  举报