java中如何靠著throw拋出一個(gè)異常來停止線程

把上面的程序return,變成自己通過throw主動(dòng)拋出異常,結(jié)果是一樣的。

例:1.5.1_1-本章源碼
馬克- to-win:馬克 java社區(qū):防盜版實(shí)名手機(jī)尾號(hào): 73203。
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) {
        }
        mt.setStop(true);
    }
}

輸出結(jié)果:

i = 0
Exception in thread "Thread-0" java.lang.ArithmeticException: divide by 0
    at MyThreadMark_to_win.run(Test.java:7)
i = 1
退出了