Java Multithreading (eight) Why stop and suspend are deprecated

Source: Internet
Author: User

Reprint Please specify source: http://blog.csdn.net/xingjiarong/article/details/47984659


The initial Java version defines a stop method to terminate a thread that also defines a suspend method to block one thread until another thread calls the Resume method. These two methods are deprecated after Java SE 1.2, because neither of these methods is secure, so let's discuss why it is unsafe and what should be done.


One, why is the Stop method not safe


In fact, the stop method is inherently unsafe because it forces the execution of the thread thread when it terminates, regardless of whether the run method is executed, and also frees all lock objects held by the thread. This behavior is seen by other threads that are blocked by the request lock, so that they continue to execute down. This will result in inconsistent data, we still take the bank transfer as an example, we still from a account to B account transfer 500 yuan, we discussed before, this process is divided into three steps, the first step is to subtract 500 from a account, if the thread is stop, then this thread will release it acquired Lock, Then the other threads continue to execute, so that the a account is inexplicably less 500 yuan and B account did not receive money. This is the non-security of the Stop method.


Ii. why the Suspend method is deprecated


The reason suspend is deprecated is because it causes deadlocks. The Suspend method is not the same as the Stop method, it does not break the object and force release the lock, but instead it keeps the lock occupied until the other thread calls the Resume method before it continues down.

If there is a A, a, two threads, a thread after acquiring a lock is suspend blocked, then a can not continue to execute, thread B after or the same lock can call the Resume method will wake a, but at this time the lock is a possession, B can not continue to execute, it will not be timely wake a, at this time a, b Two threads are unable to continue down execution and form a deadlock. That's why suspend was discarded.



Third, how to properly terminate a thread


Class MyThread extends Thread {public volatile Boolean flag = True;public void Run () {while (flag) {System.out.println ("thread Executing "), try {thread.sleep ($);} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}} SYSTEM.OUT.PRINTLN ("thread terminated");}} public class Main {public static void main (string[] args) {MyThread MyThread = new MyThread (); Mythread.start (); try {Thread . Sleep (3000);} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} Mythread.flag = false; System.out.println ("Main thread end! ");}}

We can set a conditional variable, the Run method of the while loop will constantly detect the value of the flag, where you want to end the thread to set the value of flag to False is OK! Note that the flag is set to Volitale, because Volitale can guarantee the validity of the data, if not set, it may cause the child thread to perform a more error, for example, the child thread will read flag to its own thread stack, the flag value is true, at this time the child thread surrender execution right , the operating system will give execution to the main thread, the main thread to perform flag=false operation, I hope the child thread will not be executed again, but this changes the child thread is not visible, so the child thread is also executed down again, and then re-read the value of flag will be terminated.


Of course, you can also encapsulate all operations on flag in the Synchronized keyword-modified method to achieve mutually exclusive access, or you can achieve the same effect.


Iv. how to properly block threads


If you want to secure a blocking thread, introduce a variable suspendrequested and test it in a safe place in the Run method, where the thread is not blocking the objects that other threads need. When the thread discovers that the variable has been set, it will remain waiting until it is obtained again.


Public volatile Boolean suspendrequested = false;private Lock suspendlock = new Reentrantlock ();p rivate Condition SUSPENDC Ondition = Suspendlock.newcondition ();p ublic void Run () {while (true) {if (suspendrequested) {suspendlock.lock (); try { while (suspendrequested) suspendcondition.await ();} catch (Exception e) {} finally {Suspendlock.unlock ();}}}} public void Requestsuspend () {suspendrequested = true;} public void Requestresume () {suspendrequested = False;suspendlock.lock (); try {suspendcondition.signalall ();} catch ( Exception e) {e.printstacktrace ();} finally {Suspendlock.unlock ();}}



Copyright NOTICE: This article for Bo Master original article, reproduced please indicate the source, view the original article, please visit: Http://blog.csdn.net/xingjiarong

Java Multithreading (eight) Why stop and suspend are deprecated

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.