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

Java 学习笔记之 Sleep停止线程

时间:2017-10-15 14:22:18      阅读:228      评论:0      收藏:0      [点我收藏+]

标签:dex   out   alt   结果   thread   pre   res   trace   nts   

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();
        }
    }
}

运行结果:

技术分享

 

Java 学习笔记之 Sleep停止线程

标签:dex   out   alt   结果   thread   pre   res   trace   nts   

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

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