interrupt()、interrupted()、isInterrupted()區別

 

# 線程中斷方法
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);

    }

 

 

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);

    }

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章