First, Condition class
In front of us we learned about thread waits (object.wait) and thread notifications (object.notify) with synchronized lock mates, so for JDK1.5 Java.util.concurrent.locks.ReentrantLock Lock, the JDK also provides us with a class java.util.concurrent.locks.Condition corresponding to this feature. Condition and re-entry locks are a condtion instance that is bound by the Lock.newcondition () method with the current re-entry lock, and we notify the instance to control the thread's wait and notification. All methods of the interface:
Public InterfaceCondition {//causes the current thread to join the await () wait queue, and releases the lock when another thread calls signal () to re-request it. Similar to Object.wait (). voidAwait ()throwsinterruptedexception; //This method is called if the current thread has successfully obtained a re-entry lock that is bound to the condition object, otherwise it throws a illegalmonitorstateexception when the method is called. //after the method is called, the only way to end the wait is for other threads to call the signal () or Signalall () method of the Conditional object. If the current thread is interrupted during the wait, the method continues to wait while preserving the interrupt state of the thread. voidawaituninterruptibly (); //This method is called if the current thread has successfully obtained a re-entry lock that is bound to the condition object, otherwise it throws a illegalmonitorstateexception when the method is called. //nanostimeout Specifies the maximum time (in nanoseconds) that the method waits for a signal. If signal () or Signalall () is received within the specified time, the return nanostimeout minus the time that has been waited;//If another thread interrupts the thread within a specified time, it throws a interruptedexception and clears the interrupt state of the current thread, or returns 0 or a negative number if no notification is received within the specified time. LongAwaitnanos (LongNanostimeout)throwsinterruptedexception; //basically consistent with await (), the only difference is that the method returns False when the signal () or signalall () signal is not received within the specified time, or when the thread interrupts, and the other condition returns true. BooleanAwaitLongTime, Timeunit unit)throwsinterruptedexception; //The applicable conditions and behavior are exactly the same as Awaitnanos (long nanostimeout), except that it is not waiting for a specified time, but instead waits for a moment specified by the parameter. BooleanAwaituntil (Date deadline)throwsinterruptedexception; //wakes up a thread in the await () wait queue. Similar to Object.notify () voidsignal (); //wakes up await () waits for all threads in the queue. Similar to Object.notifyall () voidSignalall ();}Second, use
1, await () wait with singnal () notice
1 PackageCom.jalja.org.base.Thread;2 3 ImportJava.util.concurrent.TimeUnit;4 Importjava.util.concurrent.locks.Condition;5 ImportJava.util.concurrent.locks.ReentrantLock;6 7 /**8 * Condition with lock to implement thread waiting and notification9 */Ten Public classconditiontest{ One Public StaticReentrantlock lock=NewReentrantlock (); A Public StaticCondition Condition =lock.newcondition (); - Public Static voidMain (string[] args) { - NewThread () { the @Override - Public voidrun () { -Lock.lock ();//Request Lock - Try{ +System.out.println (Thread.CurrentThread (). GetName () + "= =" Enter Wait "); -Condition.await ();//sets the current thread to enter the wait +}Catch(interruptedexception e) { A e.printstacktrace (); at}finally{ -Lock.unlock ();//Release Lock - } -System.out.println (Thread.CurrentThread (). GetName () + "= =" Continue execution "); - } - }.start (); in NewThread () { - @Override to Public voidrun () { +Lock.lock ();//Request Lock - Try{ theSystem.out.println (Thread.CurrentThread (). GetName () + "=" entry "); *Thread.Sleep (2000);//rest for 2 seconds . $Condition.signal ();//a thread in a random wake-up wait queuePanax NotoginsengSystem.out.println (Thread.CurrentThread (). GetName () + "End of Break"); -}Catch(interruptedexception e) { the e.printstacktrace (); +}finally{ ALock.unlock ();//Release Lock the } + } - }.start (); $ } $}
Execution Result:
thread-0=="Enter wait for thread-1=" into thread-1 break end thread-0== "continue to execute
Process: In calling the await () method the thread must obtain a re-entry lock (the 17th line of code), and after calling the await () method The threads will release the currently occupied lock. Similarly, when calling the signal () method, the thread must also get a corresponding re-entry lock (code 32 line), and the signal () method will wake up from the condition.await () wait queue. When the thread is awakened, it attempts to regain the re-entry lock it is bound to, and will continue to execute once the fetch succeeds. So make sure to release the currently occupied lock (code 41 lines) after calling the signal () method so that the awakened thread has the opportunity to get the lock before it can continue.
third, the use of condition in the JDK
Let's take a look at Java.util.concurrent.ArrayBlockingQueue;
Array-based blocking queue implementation, within Arrayblockingqueue, maintains a fixed-length array to cache data objects in the queue, which is a common blocking queue, in addition to a fixed-length array, the Arrayblockingqueue interior also holds two shaping variables, Identifies the position of the queue's head and tail in the array, respectively.
look at his put method:
Public voidPut (e e)throwsinterruptedexception {checknotnull (e);//null judgments on incoming elements FinalReentrantlock lock = This. Lock; Lock.lockinterruptibly ();//Synchronize the Put () method Try { while(count = = items.length)//if the queue is fullNotfull.await ();//let the thread that currently adds the element enter the wait stateInsert (e);//add behavior if another thread calls signal () to notify the thread}finally{lock.unlock ();//Release Lock } } PrivateE Extract () {Finalobject[] Items = This. Items; E x= This.<e>cast (Items[takeindex]); Items[takeindex]=NULL; Takeindex=Inc (TAKEINDEX); --count; Notfull.signal ();//wake up a thread in the condition wait queue returnx; }
Java thread lock Lock uses condition to implement thread waits (await) and notification (signal)