Java Concurrency (Wait-await-signal-notify-signalall-notifyal__java

Source: Internet
Author: User
3 Java in the lock and line up the toilet. A lock is a way of preventing resource access by other processes or threads, that is, locked resources cannot be accessed by other requests. In Java, the Sychronized keyword is used to lock an object. Like what:
public class Mystack {int idx = 0; char [] data = new CHAR[6];
Public synchronized void push (char c) {DATA[IDX] = C; idx++;}
Public synchronized char POPs () {idx--; return data[idx];}
public static void Main (String args[]) {mystack m = new Mystack ();/** the following object M is locked. Strictly speaking, all synchronized blocks of object m are added to the lock. If there is another thread t that attempts to access m, then T cannot execute the push and pop methods of the M object. */M.pop ()//object M is locked. The Java lock unlock is exactly the same as the number of people waiting for a public toilet seat. The first man went in and locked the door from the inside, and the others had to wait in line. When the first person comes out, the door will open (unlock). The second man went in, again he would lock the door from the inside, and the others would continue to wait in line. The toilet theory makes it easy to understand that a person enters a toilet seat and the toilet seat is locked, but does not cause another toilet seat to be locked, because one cannot crouch in two toilets at the same time. For Java it is said that the lock in Java is for the same object, not for class. Look at the following example:
MYSTATCK m1 = new Mystack (); Mystatck m2 = new Mystatck (); M1.pop (); M2.pop (); Locks on M1 objects do not affect M2 locks because they are not the same toilet seat. That is to say, if there are 3 threads T1,T2,T3 Operation M1, then these 3 threads can only queue on M1, assuming that another 2 threads t8,t9 operation m2, then T8,t9 will only wait on the M2. And T2 and T8 are not related, even if the M2 on the release of the lock, T1,t2,t3 may still have to queue on the M1. The reason without it, is not the same toilet seat ear. Java cannot add two locks to a block of code at the same time, unlike database locking mechanisms, a database can add several different locks to a single record.
4 When to release the lock. It is generally done after the synchronized code block (block of code locked) release the lock, you can also use wait () way to release the lock halfway. Wait () way like squat toilet to half, suddenly found the sewer blocked, must come out to stand on one side, so that repair sewer master (ready to perform a notify thread) in to dredge the toilet, dredge finished, the master shouted: "has been repaired" (notify), The comrade who had just come out heard the line again. Attention Ah, must wait for the master come out Ah, Master does not come out, who also can't enter. This means that after notify, not other threads can immediately enter the blockade area activity, but must also wait for notify code in the blockade area after the completion of the release lock, other threads can enter. Here is the wait and notify code example:
Public synchronized char pop () {char C. while (buffer.size () = 0) {try {this.wait ();/out of the toilet seat} catch (Interruptedexce Ption e) {//Ignore it ...}} c = ((Character) Buffer.remove (Buffer.size ()-1)). Charvalue (); return C; }
Public synchronized void push (char c) {this.notify ();//Notify those waiting () threads to queue again. Note: Just notify them to be queued again. Character charobj = new Character (c); Buffer.addelement (Charobj); }//execution complete, release lock. The threads that are lined up can come in. Go a little deeper. Because the wait () operation and the comrades out of the notify before the signal will not be queued, he will be watching the queue of the people (including the master of the Plumber in it). Note that the plumber can't jump in the queue, also have to go to the toilet with the same line, not to say that a person squatting half out after the plumber can suddenly come out and immediately into the repair, he and the original line of the Gang of people fair competition, because he is also a normal thread. If the plumber is in the back, then the person in front of them, found that blocked, wait, and then come out to one side, and then into a, then wait, out, stand aside, only to master into the implementation of notify. In this way, a moment of kung fu, lined up next to a pile of people, waiting for notify. Finally, the master in, and then notify, next.
1. A wait person (thread) is notified. 2. Why was he told that he was not the other one? Depends on the JVM. We cannot prejudge which one will be notified. In other words, high priority is not necessarily a priority wake-up, waiting time is not necessarily the first wake-up, all unpredictable. (Of course, if you understand the implementation of the JVM, you can predict it.) 3. He (the thread to be notified) is to be queued again. 4. Will he be in the first position of the line? The answer is: not necessarily. Will he be in line for the last? And not necessarily. However, if the thread priority is higher, then the probability of his being in front is quite high. 5. When it is his turn to re-enter the toilet seat, he will proceed from the place where the last wait () will not be performed again. The disgusting point says is, he will then Lababa, will not pull again. 6. If Master Notifyall (). Then the pile of people who came out of the queue again. Order is unknown. Java DOC says that the awakened threads won't be able to proceed until the "current thread relinquishes" lock on this object (The awakened thread cannot execute until the current thread releases the lock). This is the obvious thing to explain in the toilet seat theory.
5 Use of lockYou can lock resources with the Synchronized keyword. You can use the Lock keyword as well. It's what's new in JDK1.5. Usage is as follows:
Class Boundedbuffer {final lock lock = new Reentrantlock (); final Condition notfull = Lock.newcondition (); final conditio n notempty = lock.newcondition ();
Final object[] items = new OBJECT[100]; int Putptr, takeptr, Count;
public void put (Object x) throws Interruptedexception {Lock.lock (), try {while (count = = items.length) notfull.await (); ITEMS[PUTPTR] = x; if (++putptr = = items.length) putptr = 0; ++count; Notempty.signal (); finally {Lock.unlock ();}}
Public Object take () throws Interruptedexception {Lock.lock (), try {while (count = = 0) notempty.await (); Object x = items[takeptr]; if (++takeptr = = items.length) takeptr = 0; --count; Notfull.signal (); return x; finally {Lock.unlock ();}} (Note: This is an example of Javadoc, an implementation example of a blocking queue.) The so-called blocking queue, is a queue if full or empty, will cause the thread to block waiting. Arrayblockingqueue in Java provides out-of-the-box blocking queues and does not need to be written down specifically. The code between the Lock.lock () and the Lock.unlock () of an object will be locked. This way is better than synchronize. In short, the threads of wait are categorized. In the case of toilet-seat theory, the reason for those who have been squatting in half and waiting out of the toilet seat may be different, either because the toilet is clogged or because the toilet is out of water. When the notice (notify), you can shout: Because the toilet is blocked and waiting to come back to the queue (such as the problem of the toilet plug is resolved), or shout, because the toilet is not water waiting to come back to line up (such as the toilet is not water problem was solved). This can be controlled more finely. Unlike Synchronize's wait and notify, whether it's a toilet block or a toilet without water, you can only shout: just waiting to come in line. If the queue of people in a look, found that the toilet is only a problem solved, and their desire to solve the problem (the toilet is not water) has not been resolved, had to go back to wait (waiting), White came in to turn around, wasting time and resources. The lock mode corresponds to the synchronized:
Lock Await Signal Signalall
Synchronized Wait Notify Notifyall
Note: Do not call wait, notify, notifyall in blocks locked in lock mode.

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.