interrupt和interrupted和isInterrupted的區別


原創轉載請注明出處:https://www.cnblogs.com/agilestyle/p/11413917.html

 

interrupt

Code Demo

 1 package org.fool.thread;
 2 
 3 public class InterruptTest1 {
 4     public static void main(String[] args) {
 5         Thread thread = new Thread(new Runnable() {
 6             @Override
 7             public void run() {
 8                 for (int i = 0; i < 100000; i++) {
 9                     System.out.println(Thread.currentThread().getName() + " i = " + i);
10                 }
11             }
12         });
13 
14         thread.start();
15 
16         thread.interrupt();
17     }
18

Note:

從運行結果來看,調用interrupt方法並沒有停止線程

 

interrupted

Code Demo

 1 package org.fool.thread;
 2 
 3 public class InterruptTest2 {
 4     public static void main(String[] args) {
 5         Thread thread = new Thread(() -> {
 6             for (int i = 0; i < 10; i++) {
 7                 System.out.println(Thread.currentThread().getName() + " i = " + i);
 8 
 9                 if (i == 5) {
10                     Thread.currentThread().interrupt();
11 
12                     System.out.println("interrupted 1: " + Thread.interrupted());
13 
14                     System.out.println("interrupted 2: " + Thread.interrupted());
15                 }
16             }
17         });
18 
19         thread.start();
20 
21     }
22 }

Console Output

Note:

控制台第一次打印的結果是true,第二次為false;Java Doc中給出的解釋是:測試當前線程是否已經中斷,線程的中斷狀態由該方法清除。即如果連續兩次調用該方法,則第二次調用將返回false(在第一次調用已清除flag后以及第二次調用檢查中斷狀態之前,當前線程再次中斷的情況除外)

所以,interrupted()方法具有清除狀態flag的功能 

 

isInterrupted

Code Demo

 1 package org.fool.thread;
 2 
 3 public class InterruptTest3 {
 4     public static void main(String[] args) {
 5         Thread thread = new Thread(() -> {
 6             for (int i = 0; i < 10; i++) {
 7                 System.out.println(Thread.currentThread().getName() + " i = " + i);
 8             }
 9         });
10 
11         thread.start();
12 
13         // main thread interrupt
14         Thread.currentThread().interrupt();
15 
16         System.out.println(thread.getName() + ":" + thread.isInterrupted());
17         System.out.println(thread.getName() + ":" + thread.isInterrupted());
18         System.out.println(Thread.currentThread().getName() + ":" + Thread.currentThread().isInterrupted());
19         System.out.println(Thread.currentThread().getName() + ":" + Thread.currentThread().isInterrupted());
20 
21         // thread interrupt
22         thread.interrupt();
23 
24         System.out.println(thread.getName() + ":" + thread.isInterrupted());
25         System.out.println(thread.getName() + ":" + thread.isInterrupted());
26     }
27 }

Console Output

 

Summary

調用interrupt()方法僅僅是在當前線程中打了一個停止的標記,並不是真正的停止線程

interrupted()測試當前線程是否已經是中斷狀態,執行后具有清除中斷狀態flag的功能

isInterrupted()測試線程Thread對象是否已經是中斷狀態,但不清除中斷狀態flag 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM