一,介紹html
本文記錄JAVA多線程中的中斷機制的一些知識點。主要是stop方法、interrupted()與isInterrupted()方法的區別,並從源代碼的實現上進行簡單分析。react
JAVA中有3種方式能夠終止正在運行的線程安全
①線程正常退出,即run()方法執行完畢了多線程
②使用Thread類中的stop()方法強行終止線程。但stop()方法已通過期了,不推薦使用app
③使用中斷機制less
線程正常退出沒有什麼東東,中斷機制下面詳細介紹,先看下stop()方法的源代碼,關鍵是源代碼上的註釋。它解釋了爲何stop()不安全,stop()方法中止的是哪一個線程?ide
1 /** 2 * Forces the thread to stop executing. 3 * <p> 4 * If there is a security manager installed, its <code>checkAccess</code> 5 * method is called with <code>this</code> 6 * as its argument. This may result in a 7 * <code>SecurityException</code> being raised (in the current thread). 8 * <p> 9 * If this thread is different from the current thread (that is, the current 10 * thread is trying to stop a thread other than itself), the 11 * security manager's <code>checkPermission</code> method (with a 12 * <code>RuntimePermission("stopThread")</code> argument) is called in 13 * addition. 14 * Again, this may result in throwing a 15 * <code>SecurityException</code> (in the current thread). 16 * <p> 17 * The thread represented by this thread is forced to stop whatever 18 * it is doing abnormally and to throw a newly created 19 * <code>ThreadDeath</code> object as an exception. 20 * <p> 21 * It is permitted to stop a thread that has not yet been started. 22 * If the thread is eventually started, it immediately terminates. 23 * <p> 24 * An application should not normally try to catch 25 * <code>ThreadDeath</code> unless it must do some extraordinary 26 * cleanup operation (note that the throwing of 27 * <code>ThreadDeath</code> causes <code>finally</code> clauses of 28 * <code>try</code> statements to be executed before the thread 29 * officially dies). If a <code>catch</code> clause catches a 30 * <code>ThreadDeath</code> object, it is important to rethrow the 31 * object so that the thread actually dies. 32 * <p> 33 * The top-level error handler that reacts to otherwise uncaught 34 * exceptions does not print out a message or otherwise notify the 35 * application if the uncaught exception is an instance of 36 * <code>ThreadDeath</code>. 37 * 38 * @exception SecurityException if the current thread cannot 39 * modify this thread. 40 * @see #interrupt() 41 * @see #checkAccess() 42 * @see #run() 43 * @see #start() 44 * @see ThreadDeath 45 * @see ThreadGroup#uncaughtException(Thread,Throwable) 46 * @see SecurityManager#checkAccess(Thread) 47 * @see SecurityManager#checkPermission 48 * @deprecated This method is inherently unsafe. Stopping a thread with 49 * Thread.stop causes it to unlock all of the monitors that it 50 * has locked (as a natural consequence of the unchecked 51 * <code>ThreadDeath</code> exception propagating up the stack). If 52 * any of the objects previously protected by these monitors were in 53 * an inconsistent state, the damaged objects become visible to 54 * other threads, potentially resulting in arbitrary behavior. Many 55 * uses of <code>stop</code> should be replaced by code that simply 56 * modifies some variable to indicate that the target thread should 57 * stop running. The target thread should check this variable 58 * regularly, and return from its run method in an orderly fashion 59 * if the variable indicates that it is to stop running. If the 60 * target thread waits for long periods (on a condition variable, 61 * for example), the <code>interrupt</code> method should be used to 62 * interrupt the wait. 63 * For more information, see 64 * <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">Why 65 * are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>. 66 */ 67 @Deprecated 68 public final void stop() { 69 stop(new ThreadDeath()); 70 }
上面註釋,第9行到第16行代表,stop()方法能夠中止「其餘線程」。執行thread.stop()方法這條語句的線程稱爲當前線程,而「其餘線程」則是 調用thread.stop()方法的對象thread所表明的線程。測試
如:ui
1 public static void main(String[] args) { 2 MyThread thread = new MyThread... 3 //..... 4 thread.stop(); 5 //.... 6 }
在main方法中,當前線程就是main線程。它執行到第4行,想把「其餘線程」thread「 給中止。這個其餘線程就是MyThread類 new 的thread對象所表示的線程。this
第21行至23行代表,能夠中止一個還沒有started(啓動)的線程。它的效果是:當該線程啓動後,就立馬結束了。
第48行之後的註釋,則深入代表了爲何stop()方法被棄用!爲何它是不安全的。
好比說,threadA線程擁有了監視器,這些監視器負責保護某些臨界資源,好比說銀行的轉帳的金額。當正在轉帳過程當中,main線程調用 threadA.stop()方法。結果致使監視器被釋放,其保護的資源(轉帳金額)極可能出現不一致性。好比,A帳戶減小了100,而B帳戶卻沒有增長100
二,中斷機制
JAVA中如何正確地使用中斷機制的細節太多了。interrupted()方法與 isInterrupted()方法都是反映當前線程的是否處於中斷狀態的。
①interrupted()
1 /** 2 * Tests whether the current thread has been interrupted. The 3 * <i>interrupted status</i> of the thread is cleared by this method. In 4 * other words, if this method were to be called twice in succession, the 5 * second call would return false (unless the current thread were 6 * interrupted again, after the first call had cleared its interrupted 7 * status and before the second call had examined it). 8 * 9 * <p>A thread interruption ignored because a thread was not alive 10 * at the time of the interrupt will be reflected by this method 11 * returning false. 12 * 13 * @return <code>true</code> if the current thread has been interrupted; 14 * <code>false</code> otherwise. 15 * @see #isInterrupted() 16 * @revised 6.0 17 */ 18 public static boolean interrupted() { 19 return currentThread().isInterrupted(true); 20 }
從源碼的註釋中看出,它測試的是當前線程(current thread)的中斷狀態,且這個方法會清除中斷狀態。
②isInterrupted()
1 /** 2 * Tests whether this thread has been interrupted. The <i>interrupted 3 * status</i> of the thread is unaffected by this method. 4 * 5 * <p>A thread interruption ignored because a thread was not alive 6 * at the time of the interrupt will be reflected by this method 7 * returning false. 8 * 9 * @return <code>true</code> if this thread has been interrupted; 10 * <code>false</code> otherwise. 11 * @see #interrupted() 12 * @revised 6.0 13 */ 14 public boolean isInterrupted() { 15 return isInterrupted(false); 16 }
從源碼註釋中能夠看出,isInterrupted()方法不會清除中斷狀態。
③interrupted()方法與 isInterrupted()方法的區別
從源代碼能夠看出,這兩個方法都是調用的isInterrupted(boolean ClearInterrupted),只不過一個帶的參數是true,另外一個帶的參數是false。
1 /** 2 * Tests if some Thread has been interrupted. The interrupted state 3 * is reset or not based on the value of ClearInterrupted that is 4 * passed. 5 */ 6 private native boolean isInterrupted(boolean ClearInterrupted);
所以,第一個區別就是,一個會清除中斷標識位,另外一個不會清除中斷標識位。
再分析源碼,就能夠看出第二個區別在return 語句上:
public static boolean interrupted() { return currentThread().isInterrupted(true); } /************************/ public boolean isInterrupted() { return isInterrupted(false); }
interrupted()測試的是當前的線程的中斷狀態。而isInterrupted()測試的是調用該方法的對象所表示的線程。一個是靜態方法(它測試的是當前線程的中斷狀態),一個是實例方法(它測試的是實例對象所表示的線程的中斷狀態)。
下面用個具體的例子來更進一步地闡明這個區別。
有一個自定義的線程類以下:
1 public class MyThread extends Thread { 2 @Override 3 public void run() { 4 super.run(); 5 for (int i = 0; i < 500000; i++) { 6 System.out.println("i=" + (i + 1)); 7 } 8 } 9 }
先看interrupted()方法的示例:
1 public class Run { 2 public static void main(String[] args) { 3 try { 4 MyThread thread = new MyThread(); 5 thread.start(); 6 Thread.sleep(1000); 7 thread.interrupt(); 8 //Thread.currentThread().interrupt(); 9 System.out.println("是否中止1?="+thread.interrupted());//false 10 System.out.println("是否中止2?="+thread.interrupted());//false main線程沒有被中斷!!!
//......
第5行啓動thread線程,第6行使main線程睡眠1秒鐘從而使得thread線程有機會得到CPU執行。
main線程睡眠1s鍾後,恢復執行到第7行,請求中斷 thread線程。
第9行測試線程是否處於中斷狀態,這裏測試的是哪一個線程呢???答案是main線程。由於:
(1)interrupted()測試的是當前的線程的中斷狀態
(2)main線程執行了第9行語句,故main線程是當前線程
再看isInterrupted()方法的示例:
1 public class Run3 { 2 public static void main(String[] args) { 3 try { 4 MyThread thread = new MyThread(); 5 thread.start(); 6 Thread.sleep(1000); 7 thread.interrupt(); 8 System.out.println("是否中止1?="+thread.isInterrupted());//true
在第8行,是thread對象調用的isInterrupted()方法。所以,測試的是thread對象所表明的線程的中斷狀態。因爲在第7行,main線程請求中斷 thread線程,故在第8行的結果爲: true