码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2017-10-14 21:05:37      阅读:230      评论:0      收藏:0      [点我收藏+]

标签:exception   exit   tar   停止线程   pre   image   学习笔记   eal   string   

异常法停止线程:

 

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 学习笔记之 异常法停止线程

标签:exception   exit   tar   停止线程   pre   image   学习笔记   eal   string   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!