欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

interrupt()、interrupted()、isInterrupted()区别

程序员文章站 2022-05-04 21:39:06
...

 

# 线程中断方法
interrupt()

# interrupt()方法中断后 第一次调用interrupted(),返回true
# 之后调用interrupted()返回false,除非线程重新中断
interrupted()


# interrupt()调用后,isInterrupted()返回true
isInterrupted()

 

demo1

# demo1

 public static void main(String[] args) throws Exception{

        Thread t = new Thread(() -> {

            while (!Thread.currentThread().isInterrupted()){

                System.out.println(Thread.currentThread().getName()+" "+Thread.currentThread().isInterrupted());

            }

            System.out.println("The End ! isInterrupted="+Thread.currentThread().isInterrupted());
            System.out.println("The End ! isInterrupted="+Thread.currentThread().isInterrupted());
            System.out.println("The End ! isInterrupted="+Thread.currentThread().isInterrupted());

        });

        t.start();

        Thread.sleep(2000);

        t.interrupt();

        TimeUnit.SECONDS.sleep(60);

    }

 

interrupt()、interrupted()、isInterrupted()区别

 

demo2

public static void main(String[] args) throws Exception{

        AtomicInteger atomicInteger = new AtomicInteger(0);

        Runnable runnable = () ->{

            while (true){
                boolean interrupted = Thread.interrupted();
                if(interrupted) {
                    atomicInteger.incrementAndGet();
                    System.out.println("============================"+Thread.currentThread().getName()+" "+interrupted);
                }else {
                    if(atomicInteger.get()>0){
                        atomicInteger.incrementAndGet();
                    }
                    System.out.println("----------------------------"+Thread.currentThread().getName()+" "+interrupted);
                    if(atomicInteger.get()>5) break;
                }

            }

        };

        Thread t = new Thread(runnable);
        t.start();

        Thread.sleep(2000);
        t.interrupt();

        TimeUnit.SECONDS.sleep(60);

    }

 

interrupt()、interrupted()、isInterrupted()区别

 

 

 

相关标签: concurrent