1. 程式人生 > >Java 學習筆記之 Sleep停止線程

Java 學習筆記之 Sleep停止線程

run rgs ges xtend over exce http tac p s

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停止線程