zoukankan      html  css  js  c++  java
  • Java 学习笔记之 Sleep停止线程

    Sleep停止线程:

    在Sleep状态下被interrupt,interrupted 状态会被擦除,返回false。

    线程在Sleep状态下被interrupt:

    public class SleepInterruptThread extends Thread{
        @Override
        public void run() {
            try {
                System.out.println("run begin");
                Thread.sleep(2000000);
                System.out.println("run end");
            } catch (InterruptedException e) {
                System.out.println("Interrupt in sleep stage. Interrupted status: " + this.isInterrupted());
                e.printStackTrace();
            }
        }
    }
    
    public class ThreadRunMain {
        public static void main(String[] args) {
            testSleepInterruptThread();
        }
    
    
        public static void testSleepInterruptThread(){
            try {
                SleepInterruptThread sit = new SleepInterruptThread();
                sit.start();
                Thread.sleep(1000);
                sit.interrupt();
            } catch (InterruptedException e) {
                System.out.println("Main catch");
                e.printStackTrace();
            }
            System.out.println("end!");
        }
    }

    运行结果:

    线程在Sleep之前被interrupt:

    public class BeforeSleepInterruptThread extends Thread{
        @Override
        public void run() {
            try {
                for (int i=0;i<100000;i++){
                    System.out.println("i="+(i+1));
                }
                System.out.println("run begin");
                Thread.sleep(2000000);
                System.out.println("run end");
            } catch (InterruptedException e) {
                System.out.println("First interrupt, then sleep. Interrupted status: " + this.isInterrupted());
                System.out.println("First interrupt, then sleep. Interrupted status: " + Thread.interrupted());
                e.printStackTrace();
            }
        }
    }
    
    public class ThreadRunMain {
        public static void main(String[] args) {
            testBeforeSleepInterruptThread();
        }
    
        public static void testBeforeSleepInterruptThread(){
            try {
                BeforeSleepInterruptThread bsit = new BeforeSleepInterruptThread();
                bsit.start();
                Thread.sleep(100);
                bsit.interrupt();
                System.out.println("end!");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    运行结果:

  • 相关阅读:
    Maven的安装
    Mongodb 分库解决锁率过大问题
    IntelliJ IDEA集成开发Maven工程
    soapUI4.5模拟客户端测试webservice接口,含性能测试
    Mongodb性能监控
    Mongodb内存释放
    ActiveMq队列数据监控器1小时1个Swing小程序
    运输公司对用户计算运输费用C语言109页
    给出一百分制,要求输出成绩等级'A''B''C''D''E'
    有一函数,写程序 输入x的值,输出y相应的值
  • 原文地址:https://www.cnblogs.com/AK47Sonic/p/7669964.html
Copyright © 2011-2022 走看看