zoukankan      html  css  js  c++  java
  • 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!");
        }
    }

    运行结果:

  • 相关阅读:
    最详细的 paypal 支付接口开发--Java版
    Java IO--NIO(二)
    Java IO--NIO(一)
    Java IO--BIO
    ForkJoinPools
    ScheduledThreadPool
    SingleThread
    CachedThreadPool
    ForkJoinPool
    WorkStealingPool
  • 原文地址:https://www.cnblogs.com/AK47Sonic/p/7668244.html
Copyright © 2011-2022 走看看