Java_ Concurrent Thread _condition

Source: Internet
Author: User

1. Overview

The use of condition should be in the context of Lock, see Java_ Concurrent Threads _lock, Readwritelock. The lock object of obj is used in the synchronized synchronization code block, and then the problem of multithreading is handled with Obj.notify () and obj.wait (). However, the same lock and condition can also be used to accomplish the same function, condition only with lock use only makes sense, but lock more flexible, using the format as follows.

Lock with conditionprivate static reentrantlock lock = new Reentrantlock ();p rivate static Condition condition1 = Lock.newco Ndition (); {Lock.lock (); try{//condition1.await ();//condition1 should be called in its corresponding lock interval, waiting for other threads to call Condition1.signal ();//}finally{ Lock.unlock ();}}


2.await () and signal () principle Analysis
static final class Node {volatile node prev;    Volatile Node next;    volatile thread thread;
 Node Nextwaiter;} 
public class Conditionobject implements Condition, java.io.Serializable {/** first node of Condition queue. */private Transient node fi rstwaiter;/** last node of the condition queue.
 */private transient Node lastwaiter;//...} 
condition internally maintains a node's doubly linked list, calling Condition.await (), a new node node is created, Lastwaiter points to the newly created node object, and each time signal () is called, the node object is taken from the front of the list by Firstwaiter and the Firstwaiter points to the current Node.nextwaiter object. The node object is then judged by the operation.

(1). await ()

action: Current thread hibernation stop scheduling , whether or not to lock; Put in queue wait signal ()

/** * If the current thread is interrupted        , the Interruptedexception * block is thrown until the signal is called and the thread is interrupted */public final void await () throws Interruptedexception {        if (thread.interrupted ()) throw new Interruptedexception ();                Node node = Addconditionwaiter ();        Create a new node object, put the end of the list int savedstate = fullyrelease (node);        int interruptmode = 0;            Determines whether the synchronization queue while (!isonsyncqueue (node)) {Locksupport.park (this);        if ((Interruptmode = checkinterruptwhilewaiting (node))! = 0) break; } if (acquirequeued (node, savedstate) && interruptmode! = throw_ie) Interruptmode = REIN        Terrupt;        if (node.nextwaiter! = null)//clean up if cancelled unlinkcancelledwaiters ();    if (Interruptmode! = 0) reportinterruptafterwait (interruptmode); }

(2). Signal ()

    /**     * Moves The longest-waiting thread, if one exists, from the     * Wait queue for this condition to the wait queue For the     * owning lock.     *     * @throws illegalmonitorstateexception if {@link #isHeldExclusively}     *         returns {@code false}     */< C13/>public final void signal () {        if (!isheldexclusively ())            throw new Illegalmonitorstateexception ();        Node first = Firstwaiter;        if (first! = null)            dosignal (first);    }


3. Custom Blocking Queues
Class Boundedbuffer {final lock lock = new Reentrantlock (); final Condition notfull = Lock.newcondition (); final Condition N Otempty = 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)//wait for no slow notfull.await (); Items[putptr] = X;if (++putptr = = items.length) Putptr = 0;++count;//is not empty notempty.signal ();} finally {Lock.unlock ();}} Public Object take () throws Interruptedexception {lock.lock (); try {while (count = = 0)//Wait not empty notempty.await (); Object x = it Ems[takeptr];if (++takeptr = = items.length) Takeptr = 0;--count;//is not full notfull.signal (); return x;} finally {Lock.unlock ();}}}


4. Application examples
private static Reentrantlock lock = new Reentrantlock ();p rivate static Condition condition1 = Lock.newcondition ();p ublic s tatic void Main (string[] args) {new Thread () {@Overridepublic void run () {lock.lock (); try {//system.out.println ( Thread.CurrentThread (). GetName () + ", locked"); try {condition1.await (); System.out.println (Thread.CurrentThread (). GetName () + ", awaited");} catch (Interruptedexception e) {e.printstacktrace ();} System.out.println (Thread.CurrentThread (). GetName () + ", 'll finally");} finally {System.out.println (Thread.CurrentThread (). GetName () + ", finally"); Lock.unlock (); System.out.println (Thread.CurrentThread (). GetName () + ", unlocked");}}. Start (); new Thread () {@Overridepublic void run () {lock.lock (); try {System.out.println (Thread.CurrentThread (). GetName () + ", locked"); condition1.signal ();//But no lock is released, wait for Lock.unlock (), condition1 corresponding thread is awakened, Same as Synchronized System.out.println (Thread.CurrentThread (). GetName () + ", 'll finally");} finally {System.out.println (thread.currentthread(). GetName () + ", finally"), try {thread.sleep (ten);} catch (Interruptedexception e) {e.printstacktrace ();} System.out.println (Thread.CurrentThread (). GetName () + ", unlocked"); Lock.unlock ();}}. Start ();} /* *thread-1, LockedThread-2, LockedThread-2, 'll finallyThread-2, FinallyThread-2, UnlockedThread-1, awaitedThread-1 , would finallyThread-1, finallyThread-1, unlocked * *

Java_ Concurrent Thread _condition

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.