java中如何靠着throw抛出一个异常来停止线程

把上面的程序return,变成自己通过throw主动抛出异常,结果是一样的。 

例:1.5.1_1

class MyThreadMark_to_win extends Thread{
    private boolean stop;
    public void run() {
        for (int i = 0; i < 100; i++) {
            if (stop) {
                System.out.println("退出了");
                throw new ArithmeticException("divide by 0");
            }
            try {
                Thread.sleep(200);
            } catch (Exception e) {
                e.printStackTrace();

            }
            System.out.println("i = " + i);
        }
    }

    public void setStop(boolean stop) {
        this.stop = stop;
    }
}

public class Test {
    public static void main(String[] args) {
        MyThreadMark_to_win mt = new MyThreadMark_to_win();
        mt.start();
        try {
            Thread.sleep(300);
        } catch (Exception e) {   

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

 
————————————————
版权声明:本文为CSDN博主「mark_to_win」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/mark_to_win/article/details/70141470

posted @ 2021-03-30 11:20  小龙虾1  阅读(246)  评论(0)    收藏  举报