Java multi-thread wait () and notirfy () Analysis

Source: Internet
Author: User

Class threada
{
Public static void main (string [] ARGs)
{
Threadb B = new threadb ();
B. Start ();
System. Out. println ("B is start ....");
Synchronized (B) // What does B in parentheses mean and what does it do?
{
Try
{
System. Out. println ("waiting for B to complete ...");
B. Wait (); // What does this sentence mean?
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, we must first understand y () and wait (). Why didn't we record the two methods when recording the thread a few days ago?
Thread class, but belongs to the underlying object base class. That is to say, not only is thread, but every object has y and wait functions. Why? Because they use
To manipulate the lock, and each object has a lock. The lock is the basis of each object. Since the lock is the basis, the method to manipulate the lock is of course the most basic.

Let's take a look at it. First, we 'd better review Part 1 of think in Java 14.3.1: waiting and notification, that is, wait () and policy.

According to think in Java, "Wait () allows us to put threads into the" Sleep "state, while actively waiting for conditions to change. in addition, the thread will be awakened only when one notify () or notifyall () Change and check whether the conditions have changed."

Let's explain this sentence.
"Wait () allows us to put the thread into the" Sleep "State. That is to say, wait also blocks the current thread, which is the same as sleep or suspend. what is the difference between it and sleep and suspend?


The difference is that "(wait) and" actively "Wait for the condition to change", this is critical, and sleep and suspend cannot be done, because sometimes we need to synchronize
(Synchronized) helps prevent conflicts between threads. Once synchronization is used, the object is locked, that is, the object lock is obtained. Other threads that want to use the object lock can only wait in the queue,
Wait until all the synchronization methods or programs in the synchronization block are run. in the synchronization method and synchronization block, neither sleep () nor suspend () can be called independently to unlock the lock.
They all occupy the Object locks being used.
However, wait does. It allows the synchronization method or synchronization block to temporarily discard the object lock and temporarily give it to other persons who need the object lock (Here it should be a program block or thread) for use, this means that other Synchronization Methods in the thread object can be called during wait () execution! In other cases (sleep, suspend), this is impossible.
But pay attention to what I mentioned above. I just temporarily give up the object lock and use it for other threads. The thread where my wait is located still needs to reclaim this object lock. What is wait? It's wait. I can get it back when someone else finishes using it!
Well, how can we take back the object lock?
The first method is to limit the lending time. set the parameter in wait (), for example, wait (1000). in milliseconds, it indicates that I only lent out for 1 second. After one second, I automatically took it back.
The second method is to let the borrower inform me that he has used up his work and will return it to me. at this time, I will immediately withdraw it. ah, what if I took it back one hour later and it took only half an hour for someone else to finish it? Depend! Of course, it will be recovered after it is used up. It also determines how long it will take.

So how can someone tell me? I believe everyone can think of it, notify (), this is the last sentence "and only when a notify () or notifyall () changes, the thread will be awakened.
Therefore, we can place a wait () and Policy () in any synchronous method or within the synchronization block, regardless of whether the class is prepared for thread-related processing. In fact, we can only call wait () and Policy () in the synchronous method or block ().

At this time, it is easy to explain the above program.


Synchronized (B) {...}; defines a synchronization block and uses B as the resource lock. B. Wait (); Means to temporarily release the lock and block the current thread so that it can
The thread that uses the same lock has the opportunity to execute it. Here, the thread B must use the same lock. after this thread is executed to a certain point, it notifies the wait thread by running y (). The lock has been used up,
After the synchronization block of policy () is run, the thread of wait can continue to run.

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.