Multi-thread Java thread blocking and wake-up

Source: Internet
Author: User

The blocking and wakeup of threads is a key point in multithreaded concurrency, and when the number of threads reaches a large order of magnitude, concurrency can lead to a lot of hidden problems. How to properly pause a thread, and then how to resume at a required point in time, requires careful consideration of the details. In the history of Java, the suspend (), resume () method was used to wake up the thread, but there were a lot of problems, more typical or deadlock problem. In the following code, the main logic code is that the primary thread starts the thread MT for a period of time after attempting to use suspend () to suspend the thread and finally resumes the thread using resume (). But the reality is not as expected, the implementation to suspend () will stay stuck, you can't wait to "canyou get here?" The output.

public class Threadsuspend {

public static Voidmain (string[] args) {

Thread MT = Newmythread ();

Mt.start ();

try {

Thread.CurrentThread (). Sleep (100);

} catch (Interruptedexception e) {

E.printstacktrace ();

}

mt.suspend ();

System.out.println ("Canyou get here?");

Mt.resume ();

}

Static class Mythreadextends Thread {

public void Run () {

while (true) {

System.out.println ("Running ...");

}

}

}

}

The phenomenon described above is actually caused by a deadlock, it does not seem to be a problem, the thread's task is simply to print a string, the root cause of the problem is hidden deeper, the main thread started the thread MT, the threads MT began to execute the Execute () method, continuously print the string, The problem is that the System.out.println, because Println is declared as a synchronous method, executes a synchronous lock on the system class's out (one instance of the PrintStream Class) singleton attribute, and suspend () Method suspends the thread but does not release the lock, the thread MT is suspended after the main thread calls SYSTEM.OUT.PRINTLN also need to obtain the synchronization lock of the system class out object to print "Can get here?", the main thread has been waiting for the synchronization lock and the MT thread does not release the lock, This leads to the creation of deadlocks.

Visible suspend and resume have a deadlock tendency, accidentally will cause many problems, and even cause the whole system to crash. Perhaps, the solution can use blocking that targets objects, that is, using the Wait () and notify () methods of the object class to implement thread blocking. The blocking programming thinking of object needs a little transformation, which is quite different from the thread-oriented blocking thinking, such as the previous suspend and resume can complete the suspend recovery operation simply by calling directly within the threads, which is very well understood, and if you use wait, Notify form through an object as a signal, can be seen as a door, object's Wait () method is the door lock action, notify () is the action of the door, a thread once closed the door after the other threads will block until other threads open the door. 2-5-8-4, an object called by the Wait () method is like plugging a door, line Cheng, line Cheng will block, thread three calls the object's notify () method to open the door (exactly called the Notifyall () method, notify () Just let thread one or thread two one thread pass), line Cheng, thread two can pass.

Figure 2-5-8-4

Using wait and notify can circumvent the deadlock problem, but it is not entirely avoidable and must be avoided during the programming process. Some points to note during use are: First, the wait, the Notify method is for the object, and the Wait () method that calls any object will cause the thread to block, and the lock on the object will be freed, and the Notify () of any object is called accordingly. The method will randomly dismiss the thread that the object is blocking, but it needs to regain the lock of the object until it succeeds, and second, the wait, notify method must be called in the synchronized Block or method, and ensure that the lock object of the synchronization block or method is called with the wait, The object of the Notify method is the same, so that the current thread has successfully acquired a lock on an object before the wait call, and when the wait block is executed, the pre-fetch object lock is freed by the front-end process. Of course, if you do not write according to the above rules, the program can be compiled, but the runtime will throw illegalmonitorstateexception exceptions, must be written to ensure that the usage is correct; Finally, notify is a random wake up of a blocked thread and let it get the object lock, Then the notifyall is to wake up all the threads in the block, let them compete for the object lock, and the thread that gets to the lock can execute down.

Through wait, notify transformation above example, the code is as follows, the idea of transformation is to add an identity variable in the mythread, once the variable is changed to call wait and notify to block the wake-up thread, because after the wait will be released synchronized ( This) locks the object lock at this time System.out.println ("Running ..."); The system class out object has no deadlock problem.

Publicclass threadwait {

public static void Main (string[] args) {

MyThread MT = new MyThread ();

Mt.start ();

try {

Thread.CurrentThread (). Sleep (10);

} catch (Interruptedexception e) {

E.printstacktrace ();

}

Mt.suspendthread ();

System.out.println ("Can you gethere?");

try {

Thread.CurrentThread (). Sleep (3000);

} catch (Interruptedexception e) {

E.printstacktrace ();

}

Mt.resumethread ();

}

}

Classmythread extends Thread {

public Boolean stop = false;

public void Run () {

while (true) {

Synchronized (this) {

System.out.println ("Running ...");

if (stop)

try {

Wait ();

} catch (Interruptedexception e) {

E.printstacktrace ();

}

}

}

}

public void SuspendThread () {

This.stop = true;

}

public void ResumeThread () {

Synchronized (this) {

This.stop = false;

Notify ();

}

}

}

The way that wait and notify is combined looks like a good solution, but its object-oriented body is the objects, blocking the current thread, and waking up to a random thread or all of the threads, favouring communication interactions between threads. If a different angle, the subject is a thread, I can easily wake up the specified thread to block, this time need locksupport, it provides the park and Unpark method for blocking and wake, and it provides to avoid deadlocks and race conditions, A good substitute for suspend and resume combinations. Using park and Unpark to transform the above example, the code is as follows:

public class Threadpark {

public static Voidmain (string[] args) {

MYTHREADMT = new MyThread ();

Mt.start ();

try {

Thread.CurrentThread (). Sleep (10);

} catch (Interruptedexception e) {

E.printstacktrace ();

}

Mt.park ();

System.out.println ("Canyou get here?");

try {

Thread.CurrentThread (). Sleep (3000);

} catch (Interruptedexception e) {

E.printstacktrace ();

}

Mt.unpark ();

}

Static Classmythread extends Thread {

Privateboolean Ispark=false;

Publicvoid Run () {

while (true) {

if (Ispark)

Locksupport.park ();

System.out.println ("Running ...");

}

}

public void Park () {

Ispark=true;

}

public void Unpark () {

Ispark=false;

Locksupport.unpark (this);

}

}

}

The blocking of the subject into threads seems to be pleasing to the eye, and because of the finer particle size controlled by park and the Unpark method, it is possible to determine exactly which thread stops at a certain point, thus avoiding the generation of deadlocks. For example, in this example, the execution of the System.out.println front thread is blocked, so there is no deadlock caused by competing for the system class out object, even if the line friend blocking after the execution of the SYSTEM.OUT.PRINTLN does not have a deadlock problem because the lock is released.

The Locksupport class provides the basis for thread-blocking wakeup, and it has the incomparable advantage of wait and notify on the issue of competitive conditions. When you use the wait and notify combinations, a thread must ensure that it has been executed to the wait wait point before it is notify by another line, that missing notify may be waiting forever, and notify cannot guarantee that a specified thread will wake up. Locksupport, because Park and Unpark introduced a licensing mechanism, the license logic is: ①park will be allowed to block at the time equal to 0, 1 is the time to return and reduce the license to 0;②unpark attempt to wake up the thread, license plus 1. According to these two logic, for the same thread, park and Unpark order does not seem to affect the execution of the program correctly, if the Unpark operation is performed first, the license is 1, then the park operation, because the license equals 1 directly back down execution, do not perform blocking operations.

Finally, the Locksupport Park and the Unpark combination really decouple the synchronization between threads, no additional object variable storage states are required, and there is no need to consider synchronous locks, and wait and notify to ensure that a lock is required to execute. Moreover, after performing the notify operation to release the lock and throw the current thread into the waiting queue of the object lock, Locksupport does not take into account the object, lock, wait queue and so on.

Multi-thread Java thread blocking and wake-up

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.