ホームページ  >  記事  >  Java  >  JAVA マルチスレッド割り込みメカニズム stop()、interrupted()、isInterrupted()

JAVA マルチスレッド割り込みメカニズム stop()、interrupted()、isInterrupted()

高洛峰
高洛峰オリジナル
2017-01-05 16:35:421433ブラウズ

まずはじめに

この記事では、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() メソッドを呼び出すオブジェクト スレッドによって表されるスレッドです。

例:

public static void main(String[] args) {
MyThread thread = new MyThread...
//.....
thread.stop();
//....
}

main メソッドでは、現在のスレッドがメイン スレッドです。 4 行目まで実行され、「他のスレッド "thread" を停止したいと考えています。この他のスレッドは、新しい MyThread クラスのスレッド オブジェクトによって表されるスレッドです。

21 行目から 23 行目は、まだ停止していないスレッドを停止できることを示しています。まだ開始されている (started) スレッドです。その結果: スレッドが開始されると、すぐに終了します

stop() メソッドが廃止される理由が明確に示されています

たとえば、threadA スレッドにはモニターがあります。これは、銀行送金の金額など、特定の重要なリソースを保護する役割を果たします。送金の進行中、メインスレッドは 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);
}

現在のスレッドをテストしていることがわかります。

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

つまり、最初の違いは、一方は割り込みフラグ ビットをクリアし、もう一方は割り込みフラグ ビットをクリアしません。

ソースコードを分析すると、2 番目の違いが return ステートメントにあることがわかります。

public static boolean interrupted() {
return currentThread().isInterrupted(true);
}
/************************/
public boolean isInterrupted() {
return isInterrupted(false);
}

interrupted() は現在のスレッドをテストし、isInterrupted() はオブジェクトによって表されるスレッドをテストします。このメソッドを呼び出すものは静的メソッド (現在のスレッドの中断ステータスをテストする) であり、もう 1 つはインスタンス メソッド (インスタンス オブジェクトによって表されるスレッドをテストする) です。以下では、具体的な例を使用します。この違いをさらに明確にしてください。次のようなカスタム スレッド クラスがあります。

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 行目はスレッド スレッドを開始し、6 行目はメイン スレッドをスリープさせます。スレッドが CPU を実行できるように 1 秒間待機します。

メインスレッドは 1 秒間スリープした後、7 行目まで実行を再開し、スレッドスレッドの中断を要求します。

行 9 は、スレッドが中断状態にあるかどうかをテストします。ここでテストされているのはどのスレッドですか? ? ?答えはメインスレッドです。理由:

(1) Interrupted() は現在のスレッドの割り込みステータスをテストします

(2) メインスレッドがステートメントの 9 行目を実行したため、メインスレッドが現在のスレッドになります

の例を見てみましょう。 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 行目は、スレッド オブジェクトによって呼び出される isInterrupted() メソッドです。したがって、テストされるのは、スレッド オブジェクトによって表されるスレッドの中断ステータスです。 7 行目でメインスレッドがスレッドスレッドの割り込みを要求しているため、8 行目の結果は true になります

その他の JAVA マルチスレッド割り込みメカニズム stop()、interrupted()、isInterrupted() 関連記事については、ご注意ください。 PHP中国語ネットへ!

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。