Java multi-thread interrupt mechanism stop (), Interrupted (), isinterrupted () _java

Source: Internet
Author: User
Tags deprecated instance method thread class

First, introduce

This article records some of the knowledge points of the interrupt mechanism in Java multithreading. It is mainly the difference between the Stop method, the interrupted () and the Isinterrupted () method, and makes a simple analysis from the realization of the source code.

There are 3 ways to terminate a running thread in Java

① thread quits normally, the run () method is finished

② uses the Stop () method in the thread class to force a thread to terminate. However, the Stop () method has expired and is not recommended for use

③ Use interrupt mechanism

Thread normal exit Nothing, interrupt mechanism the following details, first look at the Stop () method source code, the key is the source code comments. It explains why the stop () is not secure and which thread the stop () method stops.

/** * Forces the thread to stop executing. * <p> * If There is a security manager installed, the ITS <code>checkAccess</code> * the is called with & Lt;code>this</code> * as its argument.
This could result in a * <code>SecurityException</code> being raised (in the current thread). * <p> * If This thread are different from the ' current ' thread ' is ', the current * ' trying to stop a threa D than itself), the * Security manager ' s <code>checkPermission</code> A * <code>runti
Mepermission ("Stopthread") </code> argument) is called in * addition.
* Again, this could result in throwing a * <code>SecurityException</code> (in the current thread). * <p> * The thread represented by this thread are forced to stop whatever * it are doing abnormally and to throw a new
Ly 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> * A application should not normally try-catch * <code>ThreadDeath</code> unless it must do som E Extraordinary * Cleanup operation (Note this throwing of * <code>ThreadDeath</code> causes <code>f Inally</code> clauses of * <code>try</code> statements to be executed before the thread * officially die  s). If a <code>catch</code> clause catches a * <code>ThreadDeath</code> object, it is important to
Rethrow the * object so this thread actually dies. * <p> * The top-level error handler that reacts to otherwise uncaught * Exceptions does not print out a message or O
Therwise notify the * application if the uncaught exception is a instance of * &LT;CODE&GT;THREADDEATH&LT;/CODE&GT;.
* * @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 is inherently unsafe. Stopping a thread with * thread.stop causes it to unlock all of the monitors that it * has locked (as a natural consequenc E of the unchecked * <code>ThreadDeath</code> exception propagating up the stack).  If * Any of the "objects previously protected by" monitors were in * a inconsistent state, the damaged objects Visible to * the threads, potentially resulting in arbitrary behavior. Many * Uses of <code>stop</code> should is replaced by code this simply * modifies some variable to indicate t Hat the target thread should * stop running. The target thread should check this is variable * regularly, and return from its run to an orderly fashion * if the VA Riable indicates that it's to stop running. If the * target threadWaits for long periods (in a condition variable, * For example), the <code>interrupt</code> method should is U
SED to * interrupt the wait. * For more information, <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 ());}

Note above, lines 9th through 16th indicate that the stop () method can stop "other threads". The thread that executes the Thread.stop () method of this statement is called the current thread, while "Other threads" is the thread represented by object thread that calls the Thread.stop () method.

Such as:

public static void Main (string[] args) {
mythread thread = new Mythread ...
//.....
Thread.stop ();
//....
}

In the main method, the current thread is the main thread. It executes to line 4th and wants to stop the "thread of other threads". This other thread is the thread represented by a thread object of the Mythread class new.

Lines 21st through 23 indicate that you can stop a thread that has not been started (started). The effect is that when the thread starts, it ends immediately.

The comment after line 48th is a deep indication of why the Stop () method is deprecated! Why it's not safe.

For example, a Threada thread has a monitor that protects certain critical resources, such as the amount of money transferred by a bank. When the transfer process is in progress, the main thread invokes the Threada.stop () method. As a result, the monitor is released, and the resources it protects (the amount of money transferred) are likely to be inconsistencies. For example, a account was reduced by 100, while the B account did not increase by 100.

Ii. mechanism of interruption

There are too many details about how to use the interrupt mechanism correctly in Java. Both the interrupted () method and the Isinterrupted () method reflect whether the current thread is in the interrupted state.

①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 it is called twice in succession and the
* Second call would return False (Unle SS the current thread were
* interrupted again, after the ' the ' the ' I call ' had cleared its interrupted
* status and BEFO Re the second call had examined it).
*
* <p>a thread interruption ignored because A thread is not alive * at the time of the interrupt'll be
R Eflected 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);
}

As you can see from the source notes, it tests the interrupt state of the current thread, and this method clears the interrupt state.

②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 is not alive * at the time of the interrupt'll be
R Eflected 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);
}

As you can see from the source note, the isinterrupted () method does not clear the interrupt state.

The difference between the ③interrupted () method and the Isinterrupted () method

As you can see from the source code, both of these methods are called isinterrupted (Boolean clearinterrupted), except one with a parameter of true and the other with false.

/**
* Tests If some Thread has been interrupted. The interrupted state
* was reset or not based on the value of clearinterrupted this is
* passed.
*
Private Native Boolean isinterrupted (Boolean clearinterrupted);

Therefore, the first difference is that one clears the interrupt identity bit and the other does not clear the interrupt identity bit.

Re-analyze the source, you can see the second difference on the return statement:

public static Boolean interrupted () {return
CurrentThread (). isinterrupted (True);
}
/************************/Public
Boolean isinterrupted () {return
isinterrupted (false);
}

Interrupted () tests the interrupt state of the current thread. Isinterrupted () tests the thread represented by the object that called the method. One is a static method (it tests the interrupt state of the current thread), and one is an instance method (it tests the interrupt state of the thread represented by the instance object).

Here's a concrete example to further illustrate the difference.

There is a custom thread class as follows:

public class Mythread extends Thread {
@Override public
void Run () {
super.run ();
for (int i =; I < i++) {
System.out.println ("i=" + (i +));}}}

First look at the example of the interrupted () method:

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 ("Do you want to stop?) = "+thread.interrupted ());//false
System.out.println (" Stop?)      = "+thread.interrupted ());//false main thread is not interrupted!!!
//......

Line 5th starts the thread thread, and 6th executes the main thread for 1 seconds so that thread threads have an opportunity to get CPU execution.

After the main thread sleeps for 1s clock, recovery executes to line 7th, requesting that the thread thread be interrupted.

Line 9th Test thread is in the interrupted state, which thread is tested here??? The answer is main thread. Because:

(1) the interrupted () test is the interrupt state of the current thread

(2) The main thread executes the 9th line statement, so the main thread is the current thread

Then look at the example of the Isinterrupted () method:

public class Run {public
static void Main (string[] args) {
try {
mythread thread = new Mythread ();
Thread.Start ();
Thread.Sleep ();
Thread.Interrupt ();
System.out.println ("Do you want to stop?) = "+thread.isinterrupted ());//true

On line 8th, is the isinterrupted () method of the thread object invocation. Therefore, the test is the interrupt state of the thread that the Threads object represents. Because the main thread requests to interrupt the thread thread on line 7th, the result on line 8th is: true

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.