Lock interface: Multi-threaded when the JDK1.5 version is upgraded, an interface lock interface is introduced.
The solution to thread safety is to use synchronous form, (synchronous code block, or synchronous function) in fact, the ultimate use of the lock mechanism.
To a later version, the lock is directly encapsulated as an object. The thread enters the synchronization is has the lock, executes, leaves the synchronization, is releases the lock.
During the later analysis of the lock, it was found that acquiring the lock, or releasing the lock, should be more clear about the lock thing. So these actions are defined in the lock, and the lock is defined as an object.
So synchronization is an implicit lock operation, and the lock object is a displayed lock operation, and its appearance replaces synchronization.
This was done in previous versions using Wait, notify, Notifyall in the object class. That is because the locks in the synchronization are arbitrary objects, so the method of waiting for the operation lock is defined in the object class.
And now the lock is the specified object lock. So the way to find a wait-and-wake mechanism is done through the lock interface. In the lock interface, there is no direct manipulation of the method waiting to be awakened, but these methods are encapsulated separately into an object. This object is condition, which encapsulates the three methods in the object in a separate package. and provides a functionally consistent approach to await (), signal (), signalall () to embody the benefits of the new version object.
< java.util.concurrent.locks > Condition interface: await (), signal (), Signalall ();
--------------------------------------------------------
Class Boundedbuffer {
Final lock lock = new Reentrantlock ();
Final Condition notfull = Lock.newcondition ();
Final Condition 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 ();
}
}
}
Java Basics-----Lock Interface