Java Inter-threading collaboration: Condition

Source: Internet
Author: User

There are some flaws in the built-in condition queue. Each built-in lock can have only one associated conditional queue, so in a class like Bounderbuffer, multiple threads may wait for different conditional predicates on the same condition queue and expose the conditional queue object in the most common lock mode. These factors make it impossible to satisfy the requirement that all waiting threads are of a uniform type when using Notifyall. If you want to write a concurrent object with multiple conditional predicates, or if you want more control over the visibility of the conditional queue, you can use the displayed lock and condition instead of the built-in lock and condition queue, which is a more flexible choice.

A condition is associated with a lock, and you want a conditional queue to be associated with a built-in lock. To create a condition, you can raise the Lock.newcondition method on the associated lock. Just as lock provides richer functionality than built-in lock-in, condition also provides richer functionality than built-in conditional queues: There can be multiple waits at each lock, conditional waits can be interruptible or non-interruptible, time-based waits, and fair or unfair queue operations.

Unlike the built-in conditional queue, there can be any number of condition objects for each lock. The condition object inherits the fairness of the associated lock object, and for a fair lock, the thread is freed from the condition.await in FIFO order.

Condition Interface:

public interface condition{    void await () throws interruptedexception;    Boolean await (long time, Timeunit unit) throws interruptedexception;    Long Awaitnanos (long nanostimeout) throws interruptedexception;    void awaituniterruptibly ();    Boolean awaituntil (Date deadline) throws Interruptedexception;    void signal ();    void Signalall ();}
Note: In the Condition object, the Wait,notify and Notifyall methods are Await,signal,signalall respectively. However, condition extends the object, so it also contains the wait and notify methods. Be sure to use the versions--await and signal.
The official use method is as follows:
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 (); }    }}
Or a practical example to explain the use of condition:
We're going to print 1-9 of these 0 numbers, the a thread first prints 1-3, then the b thread prints 4-6, and then the a thread prints 7-9. We use condition to demonstrate the workaround:
Package Com.cooperation;import Java.util.concurrent.locks.condition;import Java.util.concurrent.locks.lock;import    Java.util.concurrent.locks.reentrantlock;public class testcondition{private static int value = 1;    Private lock lock = new Reentrantlock ();    Private Condition Condition456 = Lock.newcondition ();    Private Condition Condition789 = Lock.newcondition ();                Class Threada implements runnable{@Override public void Run () {try {                Lock.lock ();                SYSTEM.OUT.PRINTLN ("First output 1-3");                while (value<=3) {System.out.println (value++);            } condition456.signal ();            } finally {Lock.unlock ();                } try {lock.lock ();                while (value<=6) {condition789.await (); } SYSTEM.OUT.PRIntln ("Output 7-9");                while (value<=9) {System.out.println (value++);            }} catch (Interruptedexception e) {e.printstacktrace ();            } finally {Lock.unlock ();            }}} class Threadb implements runnable{@Override public void Run () {try                {Lock.lock ();                while (value<=3) {condition456.await ();            }} catch (Interruptedexception e) {e.printstacktrace ();            } finally{Lock.unlock ();                } try{Lock.lock ();                System.out.println ("Output 4-6");                while (value<=6) {System.out.println (value++); } Condition789.signal ();            } finally {Lock.unlock ();        }}} public static void Main (string[] args) {testcondition test = new Testcondition ();        Thread Threada = new Thread (test.new Threada ());        Thread threadb = new Thread (test.new threadb ());        Threada.start ();    Threadb.start (); }}
Output Result:

First output 1-3123 output 4-6456 output 7-9789
If you need to use the Wait,notify,notifyall method of the object method to implement this example can be consulted: http://outofmemory.cn/java/java.util.concurrent/ Thread-sync-with-object-wait-notify-notifyall
Also can expand, Threada print 123,threadb print 456, then let Threada print 789, and finally threadb print 10 11 12. as follows:
Package Com.cooperation;import Java.util.concurrent.locks.condition;import Java.util.concurrent.locks.lock;import    Java.util.concurrent.locks.reentrantlock;public class testcondition{private static int value = 1;    Private lock lock = new Reentrantlock ();    Private Condition Condition456 = Lock.newcondition ();    Private Condition Condition789 = Lock.newcondition ();    Private Condition Condition101112 = Lock.newcondition ();                Class Threada implements runnable{@Override public void Run () {try {                Lock.lock ();                SYSTEM.OUT.PRINTLN ("First output 1-3");                while (value<=3) {System.out.println (value++);            } condition456.signal ();            } finally {Lock.unlock ();                } try {lock.lock (); while (value<=6) {ConditiOn789.await ();                } System.out.println ("Output 7-9");                while (value<=9) {System.out.println (value++);            } condition101112.signal ();            } catch (Interruptedexception e) {e.printstacktrace ();            } finally {Lock.unlock ();            }}} class Threadb implements runnable{@Override public void Run () {try                {Lock.lock ();                while (value<=3) {condition456.await ();            }} catch (Interruptedexception e) {e.printstacktrace ();            } finally{Lock.unlock ();                } try{Lock.lock ();                System.out.println ("Output 4-6");      while (value<=6)          {System.out.println (value++);            } condition789.signal ();            } finally {Lock.unlock ();                } try {lock.lock ();                while (value<=9) {condition101112.await ();            }} catch (Interruptedexception e) {e.printstacktrace ();            } finally{Lock.unlock ();                } try{Lock.lock ();                System.out.println ("Output 10-12");                while (value<=12) {System.out.println (value++);            }} finally {Lock.unlock ();        }}} public static void Main (string[] args) {testcondition test = new Testcondition (); Thread Threada = new Thread (test.newThreada ());        Thread threadb = new Thread (test.new threadb ());        Threada.start ();    Threadb.start (); }}
Output Result:

First output 1-3123 output 4-6456 output 7-9789 output 10-12101112

Java Inter-threading collaboration: Condition

Related Article

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.