sleep(),join(),yield(),wait(),区别以及线程的中断

https://www.cnblogs.com/aspirant/p/8876670.html

public class Thread3 extends Thread{
    public void run(){  
        while(true){  
            if(Thread.currentThread().isInterrupted()){  
                System.out.println("Someone interrupted me.");  
            }  
            else{  
                System.out.println("Thread is Going...");  
            }
        }  
    }  

    public static void main(String[] args) throws InterruptedException {  
        Thread3 t = new Thread3();  
        t.start();  
        Thread.sleep(3000);  
        t.interrupt();  
    }  
}

通过调用线程的interrupt()来修改interrupted标志变为true,然后通过isInerrupted()来判断是否interrupted标志

interrupted()方法判断的是当前线程是否处于中断状态。是类的静态方法,同时会清除线程的中断状态。

如果一个线程处于sleep(),wait(),join()等阻塞状态的时候,调用线程的interrupt()会使线程抛出异常,并且修改interrupted标志位false

posted @ 2019-07-13 09:23  LeeJuly  阅读(264)  评论(0)    收藏  举报