JAVA多線程當中斷機制stop()、interrupted()、isInterrupted()。本站提示廣大學習愛好者:(JAVA多線程當中斷機制stop()、interrupted()、isInterrupted())文章只能為提供參考,不一定能成為您想要的結果。以下是JAVA多線程當中斷機制stop()、interrupted()、isInterrupted()正文
一,引見
本文記載JAVA多線程中的中止機制的一些常識點。重要是stop辦法、interrupted()與isInterrupted()辦法的差別,並從源代碼的完成長進行簡略剖析。
JAVA中有3種方法可以終止正在運轉的線程
①線程正常加入,即run()辦法履行終了了
②應用Thread類中的stop()辦法強行終止線程。但stop()辦法曾經過時了,不推舉應用
③應用中止機制
線程正常加入沒有甚麼東東,中止機制上面具體引見,先看下stop()辦法的源代碼,症結是源代碼上的正文。它說明了為何stop()不平安,stop()辦法停滯的是哪一個線程?
/** * Forces the thread to stop executing. * <p> * If there is a security manager installed, its <code>checkAccess</code> * method is called with <code>this</code> * as its argument. This may result in a * <code>SecurityException</code> being raised (in the current thread). * <p> * If this thread is different from the current thread (that is, the current * thread is trying to stop a thread other than itself), the * security manager's <code>checkPermission</code> method (with a * <code>RuntimePermission("stopThread")</code> argument) is called in * addition. * Again, this may result in throwing a * <code>SecurityException</code> (in the current thread). * <p> * The thread represented by this thread is forced to stop whatever * it is doing abnormally and to throw a newly created * <code>ThreadDeath</code> object as an exception. * <p> * It is permitted to stop a thread that has not yet been started. * If the thread is eventually started, it immediately terminates. * <p> * An application should not normally try to catch * <code>ThreadDeath</code> unless it must do some extraordinary * cleanup operation (note that the throwing of * <code>ThreadDeath</code> causes <code>finally</code> clauses of * <code>try</code> statements to be executed before the thread * officially dies). If a <code>catch</code> clause catches a * <code>ThreadDeath</code> object, it is important to rethrow the * object so that the thread actually dies. * <p> * The top-level error handler that reacts to otherwise uncaught * exceptions does not print out a message or otherwise notify the * application if the uncaught exception is an instance of * <code>ThreadDeath</code>. * * @exception SecurityException if the current thread cannot * modify this thread. * @see #interrupt() * @see #checkAccess() * @see #run() * @see #start() * @see ThreadDeath * @see ThreadGroup#uncaughtException(Thread,Throwable) * @see SecurityManager#checkAccess(Thread) * @see SecurityManager#checkPermission * @deprecated This method is inherently unsafe. Stopping a thread with * Thread.stop causes it to unlock all of the monitors that it * has locked (as a natural consequence of the unchecked * <code>ThreadDeath</code> exception propagating up the stack). If * any of the objects previously protected by these monitors were in * an inconsistent state, the damaged objects become visible to * other threads, potentially resulting in arbitrary behavior. Many * uses of <code>stop</code> should be replaced by code that simply * modifies some variable to indicate that the target thread should * stop running. The target thread should check this variable * regularly, and return from its run method in an orderly fashion * if the variable indicates that it is to stop running. If the * target thread waits for long periods (on a condition variable, * for example), the <code>interrupt</code> method should be used to * interrupt the wait. * For more information, see * <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">Why * are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>. */ @Deprecated public final void stop() { stop(new ThreadDeath()); }
下面正文,第9行到第16行注解,stop()辦法可以停滯“其他線程”。履行thread.stop()辦法這條語句的線程稱為以後線程,而“其他線程”則是 挪用thread.stop()辦法的對象thread所代表的線程。
如:
public static void main(String[] args) { MyThread thread = new MyThread... //..... thread.stop(); //.... }
在main辦法中,以後線程就是main線程。它履行到第4行,想把“其他線程”thread“ 給停滯。這個其他線程就是MyThread類 new 的thread對象所表現的線程。
第21行至23行注解,可以停滯一個還沒有started(啟動)的線程。它的後果是:當該線程啟動後,就立馬停止了。
第48行今後的正文,則深入注解了為何stop()辦法被棄用!為何它是不平安的。
好比說,threadA線程具有了監督器,這些監督器擔任掩護某些臨界資本,好比說銀行的轉賬的金額。當正在轉賬進程中,main線程挪用 threadA.stop()辦法。成果招致監督器被釋放,其掩護的資本(轉賬金額)極可能湧現紛歧致性。好比,A賬戶削減了100,而B賬戶卻沒有增長100
二,中止機制
JAVA中若何准確地應用中止機制的細節太多了。interrupted()辦法與 isInterrupted()辦法都是反應以後線程的能否處於中止狀況的。
①interrupted()
/** * Tests whether the current thread has been interrupted. The * <i>interrupted status</i> of the thread is cleared by this method. In * other words, if this method were to be called twice in succession, the * second call would return false (unless the current thread were * interrupted again, after the first call had cleared its interrupted * status and before the second call had examined it). * * <p>A thread interruption ignored because a thread was not alive * at the time of the interrupt will be reflected by this method * returning false. * * @return <code>true</code> if the current thread has been interrupted; * <code>false</code> otherwise. * @see #isInterrupted() * @revised . */ public static boolean interrupted() { return currentThread().isInterrupted(true); }
從源碼的正文中看出,它測試的是以後線程(current thread)的中止狀況,且這個辦法會消除中止狀況。
②isInterrupted()
/** * Tests whether this thread has been interrupted. The <i>interrupted * status</i> of the thread is unaffected by this method. * * <p>A thread interruption ignored because a thread was not alive * at the time of the interrupt will be reflected by this method * returning false. * * @return <code>true</code> if this thread has been interrupted; * <code>false</code> otherwise. * @see #interrupted() * @revised . */ public boolean isInterrupted() { return isInterrupted(false); }
從源碼正文中可以看出,isInterrupted()辦法不會消除中止狀況。
③interrupted()辦法與 isInterrupted()辦法的差別
從源代碼可以看出,這兩個辦法都是挪用的isInterrupted(boolean ClearInterrupted),只不外一個帶的參數是true,另外一個帶的參數是false。
/** * Tests if some Thread has been interrupted. The interrupted state * is reset or not based on the value of ClearInterrupted that is * passed. */ private native boolean isInterrupted(boolean ClearInterrupted);
是以,第一個差別就是,一個會消除中止標識位,另外一個不會消除中止標識位。
再剖析源碼,便可以看出第二個差別在return 語句上:
public static boolean interrupted() { return currentThread().isInterrupted(true); } /************************/ public boolean isInterrupted() { return isInterrupted(false); }
interrupted()測試的是以後的線程的中止狀況。而isInterrupted()測試的是挪用該辦法的對象所表現的線程。一個是靜態辦法(它測試的是以後線程的中止狀況),一個是實例辦法(它測試的是實例對象所表現的線程的中止狀況)。
上面用個詳細的例子來更進一步地說明這個差別。
有一個自界說的線程類以下:
public class MyThread extends Thread { @Override public void run() { super.run(); for (int i = ; i < ; i++) { System.out.println("i=" + (i + )); } } }
先看interrupted()辦法的示例:
public class Run { public static void main(String[] args) { try { MyThread thread = new MyThread(); thread.start(); Thread.sleep(); thread.interrupt(); //Thread.currentThread().interrupt(); System.out.println("能否停滯?="+thread.interrupted());//false System.out.println("能否停滯?="+thread.interrupted());//false main線程沒有被中止!!! //......
第5行啟動thread線程,第6行使main線程睡眠1秒鐘從而使得thread線程無機會取得CPU履行。
main線程睡眠1s鐘後,恢復履行到第7行,要求中止 thread線程。
第9行測試線程能否處於中止狀況,這裡測試的是哪一個線程呢???謎底是main線程。由於:
(1)interrupted()測試的是以後的線程的中止狀況
(2)main線程履行了第9行語句,故main線程是以後線程
再看isInterrupted()辦法的示例:
public class Run { public static void main(String[] args) { try { MyThread thread = new MyThread(); thread.start(); Thread.sleep(); thread.interrupt(); System.out.println("能否停滯?="+thread.isInterrupted());//true
在第8行,是thread對象挪用的isInterrupted()辦法。是以,測試的是thread對象所代表的線程的中止狀況。因為在第7行,main線程要求中止 thread線程,故在第8行的成果為: true