Use the wait-and-policy mechanic to deal with synchronized accessing a resource
Wait-and-PolicyMachism:
1 wait & Policy canNeverBeOutSynchronized block of the releated-object (the wait and notify methods must beCorresponding object)
2 wait can release & get the lockAutomatically
TheDifferenceBetween between Y and policyall
1 When Y is wake the thread which invoke the wait-Method
2 policyall is wake all the thread waiting for the lock released
3 Why can form the thread invoking the wait-method and threads waiting for the lock released?
We know, ifSynchronized MethodIs invoked, all the other synchronized methods belong to the object can not be invoked, so the invoking threads must be blocked, and waiting the method can be invoke, so they all waite for the lock released in the list of waiting queue.
ASynchronized classIs the same;
When the specified y method occurs, the waiting one who invoked wait () be wake;
When the policyall method occurs, the waiting queue choose the most prior one to wake, can be the one invoking wait (), also can be the ones waiting the lock released;
What we should be care?
If one waiting thread is waked, its waiting condition may not be satisfied. And in the right way, it shoshould wait continuely.
How we assure this route?
-- Just as follows came from <valid tive Java> and <practical Java>
The former: never invoke wait outside a loop
Eg:
1 synchronized (OBJ ){
2 while (<condition does not hold> ){
3 Wait ();
4 // perform action appropriate to Condition
5}
6}
The later: Use spin locks to deal with wait and policyall