• 【线程控制:线程停止】


    线程停止:中断线程。 把线程的状态终止,并抛出一个InterruptedException。

    package com.shusheng.tihuzhai.test;
    
    import java.util.Date;
    
    /**
     * @author shusheng
     * @description
     * @Email shusheng@yiji.com
     * @date 2018/8/28 10:40
     */
    public class ThreadStop extends Thread {
    
        @Override
        public void run() {
            System.out.println("开始执行:" + new Date());
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
                System.out.println("线程被终止了");
            }
            System.out.println("结束执行:"+new Date());
        }
    
    }
    package com.shusheng.tihuzhai.test;
    
    /**
     * @author shusheng
     * @description
     * @Email shusheng@yiji.com
     * @date 2018/8/28 15:08
     */
    public class ThreadStopTest {
    
        public static void main(String[] args) {
            ThreadStop ts = new ThreadStop();
            ts.start();
            try {
                Thread.sleep(3000);
                ts.interrupt();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    
    }

    运行结果:

    开始执行:Tue Aug 28 15:09:16 CST 2018
    java.lang.InterruptedException: sleep interrupted
        at java.lang.Thread.sleep(Native Method)
        at com.shusheng.tihuzhai.test.ThreadStop.run(ThreadStop.java:17)
    线程被终止了
    结束执行:Tue Aug 28 15:09:19 CST 2018
    终身学习者
  • 相关阅读:
    CodeForces 706C Hard problem
    CodeForces 706A Beru-taxi
    CodeForces 706B Interesting drink
    CodeForces 706E Working routine
    CodeForces 706D Vasiliy's Multiset
    CodeForces 703B Mishka and trip
    CodeForces 703C Chris and Road
    POJ 1835 宇航员
    HDU 4907 Task schedule
    HDU 4911 Inversion
  • 原文地址:https://www.cnblogs.com/zuixinxian/p/9548376.html
Copyright © 2020-2023  润新知