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

异常法停止线程:

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!");
    }
}

运行结果:

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