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 {
。。。。。。。。。。。。。。。。。
详情请进:http://www.mark-to-win.com/index.html?content=JavaBeginner/javaUrl.html&chapter=JavaBeginner/JavaBeginner6_web.html#StopThreadByThread

猜你喜欢

转载自www.cnblogs.com/mark-to-win/p/9695747.html