java中断方法的介绍

2018-08-31  本文已影响18人  稀饭粥95

interrupt()

修改线程的中断标识,在wait、join和sleep方法下的会抛出异常InterruptedException,线程的中断状态会被jvm自动清除,线程的中断标志重新设置为false

isInterrupted()

只是简单的查询中断状态

interrupted()

静态方法。如果当前线程被中断,你调用interrupted方法,第一次会返回true。然后,当前线程的中断状态被方法内部清除了,设置为true。那么第二次调用时就会返回false。

public static boolean interrupted() {
        return currentThread().isInterrupted(true);
}

/**
     * Tests if some Thread has been interrupted.  The interrupted state
     * is reset or not based on the value of ClearInterrupted that is
     * passed.
*/
private native boolean isInterrupted(boolean ClearInterrupted);

异常处理

wait、join和sleep方法下的会抛出异常,将线程的中断标志重新设置为false
等待锁的时候不抛出异常

public class Main{
    public static byte[] lock= new byte[1];
    
    public static void main(String[] args)  {
        
        Thread th1 = new Thread("1"){
            public void run(){
                synchronized(lock){
                    System.out.println(Thread.currentThread().getName());
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        };
        Thread th2 = new Thread("2"){
            public void run(){
                synchronized(lock){
                    System.out.println(Thread.currentThread().isInterrupted());
                
                }
            }
        };
        th1.start();
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        th2.start();
        th2.interrupt();
        
    }
}
//输出
1
true
上一篇下一篇

猜你喜欢

热点阅读