Java thread synchronization problem (an example of understanding Wait () and notify ())

Source: Internet
Author: User
Tags thread class

An example of understanding Wait () and notify ()

Here is a post I saw on the CSDN forum, which involved the understanding of the concepts of synchronization, Wait (), notify (), and I tried to dissect the two methods of Waiting () and notify () based on some of the original responses and the concepts on the thought in Java. Welcome advice.

The questions are as follows:

file://analysis of this procedure, and explain, focus on speaking synchronized, wait (), notify thank you.
Class Threada
{
public static void Main (string[] args)
{
THREADB b=new threadb ();
B.start ();
System.out.println ("B is start ...");
Synchronized (b)/What is the meaning of B in brackets, and what is the effect?
{
Try
{
System.out.println ("Waiting for B to complete ...");
B.wait ()//What does this sentence mean, who is to wait?
System.out.println ("Completed.now Back to Main thread");
}catch (Interruptedexception e) {}
}
SYSTEM.OUT.PRINTLN ("Total is:" +b.total);
}
}


Class Threadb extends Thread
{
int total;
public void Run ()
{
Synchronized (This)
{
System.out.println ("THREADB is running.");
for (int i=0;i<100;i++)
{
Total +=i;
SYSTEM.OUT.PRINTLN ("Total is" +total);
}
Notify ();
}
}
}

To analyze this program, you first have to understand notify () and wait (), why did you record the thread in the past few days without recording these two methods, because these two methods are not belong to the thread class, but belong to the lowest object base class, that is, not just thread, Each object has the function of notify and wait, why. Because they are used to manipulate the lock, and each object has a lock, the lock is the basis of each object, since the lock is the basis, then the method of manipulation of the lock is of course the most basic.

Before you look down, it's best to review the first 3 parts of the 14.3.1 in the think of Java: Wait and notice, which is waiting () and notify.

As explained in the "in Java": "Wait () allows us to place the thread in the" Sleep "state while" actively "waiting for the condition to change. And only if a notify () or Notifyall () changes, the thread wakes up and checks to see if the condition has changed ."

Let's explain this sentence.
"Wait () allows us to place the thread into the sleep state, which means that the wait is also blocking the current thread, which is the same as sleeping or suspend." What difference does it make with sleep,suspend?

The difference is that "(wait) at the same time" actively "waiting for conditions to change", which is critical, sleep and suspend can not do. Because we sometimes need to synchronize (synchronized) Help to prevent conflicts between threads, and once you use synchronization, you lock objects, Which is to get the object lock, other threads that want to use the object lock can only wait until the synchronization method or the program in the synchronization block runs out. In the synchronization method and in the synchronization block, neither sleep () nor suspend () can be unlocked when it is called. They all occupy the object lock that is being used.
Wait, however, allows the synchronization method or the synchronization block to temporarily discard the object lock and give it to someone else who needs the lock on the object (this should be a program block, or thread), which means that other synchronization methods in the thread object can be invoked during wait (). In other cases (sleep, Suspend AH), it is impossible.
But notice what I said earlier, only temporarily give up the object lock, temporarily to other threads to use, I wait for the thread is still want to lock the object back to the.
Okay, so how do we get the object locked back?
The first method, which limits the time to lend. Setting parameters in Wait (), such as Waiting (1000), in milliseconds, indicates that I only borrow out of 1 seconds, and after a second, I automatically retract.
The second way, let the people who borrowed to inform me, he used up, to give me back. At this moment, I will take it back. Hey, if I set up 1 hours later, the others only spent half an hour to finish, then how to do? Damn it! Of course, used up to take back, but also how long I set the time ah.

So how do people inform me? I believe we all can think of, notify (), this is the last sentence "and only when a notify () or notifyall () change, the thread will be awakened" meaning.
Therefore, we can place a wait () and notify () inside any synchronization method or a synchronization block, regardless of whether or not the thread-related processing is prepared in that class. And in fact, we can only invoke wait () and notify () in the Sync method or the sync block.

It's easy for us to explain the above procedure at this time.

Synchronized (b) {...} means to define a synchronized block using B as a resource lock. B.wait () means a temporary release of a lock, and block the current thread so that other threads using the same lock have the opportunity to execute, where the same lock is used for the B-thread itself. This thread, after executing to a certain place, notifies the wait thread with notify (), and the lock has been used up to notify ( After the synchronization block is in place, the thread where the wait is running can continue.

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.