首页 > 编程语言 > 详细

Java 学习笔记之 异常法停止线程

时间:2017-10-14 20:28:22      阅读:298      评论:0      收藏:0      [点我收藏+]

异常法停止线程:

 

public class RealInterruptThread extends Thread {

    @Override
    public void run() {
        try {
            for (int i = 0; i < 5000000; i++) {
                if (Thread.interrupted()) {
                    System.out.println("Thread is interrupted status, I need exit.");
                    throw new InterruptedException();
                }
                System.out.println("i=" + (i + 1));
            }
        } catch (InterruptedException e) {
            System.out.println("RealInterruptThread catch InterruptedException.");
            e.printStackTrace();
        }
    }
}

public class ThreadRunMain {
    public static void main(String[] args) {
        testRealInterruptThread();
    }

    public static void testRealInterruptThread() {
        try {
            RealInterruptThread rit = new RealInterruptThread();
            rit.start();
            Thread.sleep(1000);
            rit.interrupt();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("end!");
    }
}

运行结果:

技术分享

 

Java 学习笔记之 异常法停止线程

原文:http://www.cnblogs.com/AK47Sonic/p/7668244.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!