美文网首页java多线程
多线程之理解Interrupt

多线程之理解Interrupt

作者: 初夏时的猫 | 来源:发表于2019-11-10 19:20 被阅读0次

    在学习多线程时,多多少少会看一些源码,其中interrupt经常出现,于是看了很多博客学习了一下interrupt,并对interrupt做一下总结。
    interrupt:中断。
    线程分为几种状态:新建,就绪,运行,堵塞,死亡。
    java.lang.Thread中关于interrupt的三个方法:

    private native boolean isInterrupted(boolean ClearInterrupted);
    public boolean isInterrupted() {
            return isInterrupted(false);
        }
    public static boolean interrupted() {
            return currentThread().isInterrupted(true);
        }
        public void interrupt() {
            if (this != Thread.currentThread())
                checkAccess();
    
            synchronized (blockerLock) {
                Interruptible b = blocker;
                if (b != null) {
                    interrupt0();           // Just to set the interrupt flag
                    b.interrupt(this);
                    return;
                }
            }
            interrupt0();
        }
    

    1.interrupt:给当前线程设置中断标记(只是一个标记,需要自己写逻辑中断线程)。
    2.interrupted:如果线程有中断标记则清除并返回true,否则false。
    3.isinterrupted:如果线程有中断标记返回true,否则返回false。
    注:interrupted方法内部return的是currentThread而不是调用方法的线程
    下面举个例子

    class Runner implements Runnable{
    
        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                System.out.println(i);
                if (Thread.currentThread().isInterrupted()){
                    System.out.println("第一次"+Thread.interrupted());
                    System.out.println("第二次"+Thread.interrupted());
                    break;
                }
    
            }
        }
    }
    public class Test {
        public static void main(String[] args) {
            Thread t1 = new Thread(new Runner(),"A");;
            t1.start();
            t1.interrupt();;
        }
    }
    

    运行结果


    图片.png

    相关文章

      网友评论

        本文标题:多线程之理解Interrupt

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