首頁  >  文章  >  Java  >  JAVA多執行緒之中斷機制stop()、interrupted()、isInterrupted()

JAVA多執行緒之中斷機制stop()、interrupted()、isInterrupted()

高洛峰
高洛峰原創
2017-01-05 16:35:421480瀏覽

一,介紹

本文記錄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&#39;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(啟動)的線程。

比如說,threadA執行緒擁有了一個監視器,這些監視器負責保護某些臨界資源,比如說銀行的轉帳的金額。釋放,其保護的資源(轉帳金額)很可能出現不一致性。多了。的中斷狀態,而這個方法會清除中斷狀態。區別

從原始碼可以看出,這兩個方法都是呼叫的isInterrupted(boolean ClearInterrupted),只不過一個帶的參數是true,另一個帶的參數是false。就是,一個會清除中斷標識位,另一個不會清除中斷標識位。中斷狀態。執行緒的中斷狀態)。行啟動thread線程,第6行使main線程睡眠1秒鐘從而使得thread線程有機會獲得CPU執行。

第9行測試執行緒是否處於中斷狀態,這裡測試的是哪個執行緒呢? ? ?答案是main線程。因為:

(1)interrupted()測試的是當前的執行緒的中斷狀態

(2)main執行緒執行了第9行語句,故main執行緒是當前執行緒

再看isInterrupted()方法的範例:

/**
* 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);
}

在第8行,是thread物件呼叫的isInterrupted()方法。因此,測試的是thread物件所代表的執行緒的中斷狀態。由於在第7行,main線程請求中斷thread線程,故在第8行的結果為: true

更多JAVA多線程之中斷機制stop()、interrupted()、isInterrupted()相關文章請關注PHP中文網!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn