美文网首页
java中断方法的介绍

java中断方法的介绍

作者: 稀饭粥95 | 来源:发表于2018-08-31 11:51 被阅读18次

    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
    

    相关文章

      网友评论

          本文标题:java中断方法的介绍

          本文链接:https://www.haomeiwen.com/subject/etjswftx.html