异常法和return法

来源:互联网 发布:淘宝口碑店铺 编辑:程序博客网 时间:2024/06/05 14:45

    public static void main(String[] args) {
        try {
            ExceptionStopThread thread = new ExceptionStopThread();
            thread.start();
            thread.sleep(2000);
            thread.interrupt();
        } catch (InterruptedException e) {
            System.out.println("main cactch");
            e.printStackTrace();
        }
        System.out.println("end");
    }

}


public class ExceptionStopThread extends Thread {

 @Override
    public void run() {
        super.run();
        for (int i = 0; i < 500000; i++) {
            if (this.interrupted()) {
                System.out.println("Thread stop.");
                break;
            }
            System.out.println("i = " + i);
        }
    }

}


public class ThreadTest {

此时线程可以停止,但是在for循环外加上输出语句仍然可以输出


加上输出语句


public class ExceptionStopThread extends Thread {

 @Override
    public void run() {
        super.run();
        for (int i = 0; i < 500000; i++) {
            if (this.interrupted()) {
                System.out.println("Thread stop.");
                break;
            }
            System.out.println("i = " + i);
        }

        System.out.println("outline loops, thread is not stop.");
    }

}


解决问题方法,抛出异常

public class ExceptionStopThread extends Thread {

     @Override
    public void run() {
        super.run();
        try {
            for (int i = 0; i < 500000; i++) {
                if (this.interrupted()) {
                    System.out.println("Thread stop");
                    throw new InterruptedException();
                }
                System.out.println("i = " + i);
            }
        } catch (InterruptedException e) {
            System.out.println("Catch InterruptedException");
            e.printStackTrace();
        }
    }

}


return法:

public class ReturnStopThread extends Thread {
    @Override
    public void run() {
        while (true) {
            if (this.isInterrupted()) {
                System.out.println("Thread is stop.");
                return;
            }
            System.out.println("timer = " + System.currentTimeMillis());
        }
    }

}


    public static void main(String[] args) {
       ReturnStopThread thread = new ReturnStopThread();
        thread.start();
        try {
            thread.sleep(3000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        thread.interrupt();

}


建议使用异常法实现线程的停止,因为在catch块中可以对议程的信息进行相关的处理,而且使用异常刘能更好地控制陈谷的运行流程,不至于代码中出现多个return造成污染。

注:this.interrupted() : 测试当前线程是否已经是中断状态,执行后具有将状态标识清除为false的功能。

       this.isInterrupted() : 测试线程Thread对象是否已经是中断状态,但不清除状态标志。


0 0
原创粉丝点击