Analysis on the correct stop of Java thread

Source: Internet
Author: User
Tags deprecated

Destroy and stop methods for thread error termination

Remember when the previous beginner Java, because of the lack of lock, synchronization, asynchronous and other threads of knowledge, take for granted that destroy and stop method can correctly stop Java thread execution. However, with the accumulation of work, as well as some understanding of thread safety, slowly realize that these two methods are problematic, and these two methods have already been named in Java doc is deprecated.

Destroy () This method actually did not do anything at all, just throw a nosuchmethoderror, so that the method can not terminate the thread, therefore can not look at the text business:

/** * Throws {@link nosuchmethoderror}. * * @deprecated This method is originally designed to destroy the * thread without any cleanup. Any monitors it held would has * remained locked.     However, the method was never implemented. * If if were to is implemented, it would is deadlock-prone in * much the manner of {@link #suspend}. If the target thread held * a lock protecting a critical system resource when it is * destroyed, no Threa     D could ever access this resource again. * If Another thread ever attempted to lock this resource, deadlock * would result. Such deadlocks typically manifest themselves as * "Frozen" processes. For more information, see * <a href= "{@docRoot}/: /technotes/guides/concurrency/threadprimitivedeprecation.html "> * Why is Thread.stop, Thread.Suspend and Threa     D.resume Deprecated?</a>. * @throws nosuchmethoderror always */@Deprecated PublIC void Destroy () {throw new Nosuchmethoderror (); }
for the Stop method, it is essentiallyThread not secure, itThe call to the Run method is terminated directly, and a Threaddeath error is thrown, and if the thread holds an object lock, the lock is completely released, causing the object state to be inconsistent.specific details can be seen in the official Java doc;
Deprecated. This method is inherently unsafe.  Stopping a thread with thread.stop causes it to unlock all of the monitors so it has locked (as a natural consequence of The unchecked Threaddeath exception propagating up the stack). If any of the objects previously protected by these monitors were in a inconsistent state, the damaged objects become vis Ible to other threads, potentially resulting in arbitrary behavior. Many uses of stop should be replaced by code, simply modifies some variable to indicate the target thread should Stop running. The target thread should check this variable regularly, and return from the It run method in an orderly fashion if the Variab Le indicates that it was to stop running.  If the target thread waits for long periods (on a condition variable, for example), the interrupt method should is used to Interrupt the wait. For more information, see <a target=_blank href= "http://docs.oracle.com/javase/6/docs/technotes/guides/ Concurrency/threadprimitivedepRecation.html ">why is Thread.stop, Thread.Suspend and Thread.Resume deprecated?</a>. 

correct termination of thread

after all of the above destroy and stop methods have been negated, then what is the way to terminate threads correctly and more? in general, there are two types of solutions in Java:

    • Flag, which ends with a tag in the Run method, which is not an example because of the unusual way
    • Interrupt, by an abnormal interrupt

The following is mainly for interrupt to explore.

/** * Interrupts this thread. * * <p> unless the current thread is interrupting itself, which are * always permitted, the {@link #checkAcce     SS () CheckAccess} method * of this thread was invoked, which may cause a {@link * SecurityException} to be thrown. * * <p> If This thread was blocked in an invocation of the {@link * object#wait () Wait ()}, {@link object#  Wait (long)}, or {@link * object#wait (long, int), wait (long, int)} methods of the {@link Object} * class, The or of the {@link #join ()}, {@link #join (long)}, {@link * #join (long, int)}, {@link #sleep (long)}, or {@link #sleep (lo ng, int)}, * methods of this class, then its interrupt status would be cleared and it * would receive an {@link Inte     Rruptedexception}. * * <p> If This thread was blocked in an I/O operation upon an {@link * Java.nio.channels.InterruptibleChanne L </code>interruptible * CHANNEL&LT;CODE&GT;} then the channel would be ClosEd, the thread ' s interrupt * status would be set, and the thread would receive a {@link * java.nio.channels.ClosedBy     Interruptexception}. * * <p> If This thread was blocked in a {@link java.nio.channels.Selector} * Then the thread ' s interrupt stat US'll be set and it'll return * immediately from the selection operation, possibly with a non-zero * value, Ju     St as if the selector ' s {@link * Java.nio.channels.selector#wakeup Wakeup} method were invoked. * * <p> If None of the previous conditions hold and this thread ' s interrupt * status would be set.     </p> * * <p> interrupting a thread that's not alive need not has any effect.      * * @throws SecurityException * If the current thread cannot modify this thread * * @revised 6.0 * @spec JSR-51 */public void interrupt () {if (This! = Thread.CurrentThread ()) checkAccess (        );       Synchronized (Blockerlock) {     Interruptible b = blocker;           if (b! = null) {interrupt0 ();                Just to set the interrupt flag b.interrupt (this);            Return    }} interrupt0 (); }
According to Java source code interrupt method annotation and the implementation of the method body, can be summarized as: by calling the interrupt method can make the blocking state of the thread throws an exception, that is, the interrupt method can be used to interrupt a blocking state of the thread; The change method also sets the interrupt state of the thread (note: isinterrupted () can be used to query the interrupt state).

Practice testing The Truth experiment Interrupt can break a thread that is in a non-blocking state

Code:

public class ThreadTest {/** * @param args */public static void main (string[] args) {Workthread wthread = new Workthread () ; Wthread.start (); System.out.println ("Start calling Wthread.interrupt ()"); Wthread.interrupt (); SYSTEM.OUT.PRINTLN ("End Call Wthread.interrupt ()");}} Class Workthread extends Thread {public void run () {for (int i = 0; i < byte.max_value;) {System.out.println ("worker thread Run" + (++i));}}}
Operation Result:


The actual is printed to 127 end, because too long, only intercepts the part. It can be found that the for loop runs until the value of the variable I exceeds byte.max_value.

Conclusion: Interrupt cannot interrupt a non-blocking thread.

However, we can change the idea, since previously mentioned interrupt method will set the interrupt state of the thread, then we can pass the Isinterrupt () to judge, thus the break-through process. (essentially this scenario when the flag is interrupted)

On the code, just add a flag to the workthread condition loop to Judge--isinterrupt ():

Class Workthread extends Thread {public void run () {for (int i = 0; i < byte.max_value && isinterrupted ();) {System.out.println ("worker thread Run" + (++i));}}}
Operation Result:


As a result, interrupt mates with Isinterrupt () can interrupt a non-blocking thread. Note: The essence or the sign is interrupted

Interrupt can interrupt the blocking state of a thread

On the code:

public class ThreadTest {/** * @param args */public static void main (string[] args) {Workthread wthread = new Workthread () ; Wthread.start (); System.out.println ("Start calling Wthread.interrupt ()"); Wthread.interrupt (); SYSTEM.OUT.PRINTLN ("End Call Wthread.interrupt ()");}} Class Workthread extends thread {public void run () {System.out.println ("Worker thread Sleep"); for (int i = 0; i < Byte.max_value; {try {sleep (10 * 1000); SYSTEM.OUT.PRINTLN ("Worker thread Run" + (++i));} catch (Interruptedexception e) {System.out.println ("worker thread Interruptedexception"); break;}} System.out.println ("The worker thread has finished running");}}
Operation Result:

From the program to the running result, when the worker thread enters sleep (that is, blocking), calling the interrupt method will cause the thread to throw an exception.

Conclusion: Interrupt can interrupt the blocking state of the thread.

Summarize

Java does not have a mechanism to terminate threads immediately, and the Java thread class provides destroy and stop methods that do not properly terminate threads, only through flags or Interrup methods.

Analysis on the correct stop of Java thread

Related Article

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.