JAVA thread collaboration: Condition

Source: Internet
Author: User

JAVA thread collaboration: Condition

The built-in condition queue has some defects. Each built-in lock can only have one associated condition queue. Therefore, in the BounderBuffer type, multiple threads may wait for different condition predicates on the same condition queue, in addition, the condition queue object is exposed in the most common locking mode. These factors make it impossible to meet the requirement that all the waiting threads are of a uniform type when policyall is used. If you want to write a concurrent object with multiple condition predicates, or want to gain more control besides the visibility of the condition 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, just like a Condition queue and a built-in Lock-in association. To create a Condition, you can call the Lock. newCondition method on the associated Lock. Just as locks provide more functions than built-in locks, Condition also provides more functions than built-in conditional Queues: there may be multiple waits, conditional waits that can be interrupted or non-interrupted, time-based waits, and fair or unfair queue operations for each lock.

Unlike the built-in Condition queue, each Lock can have any number of Condition objects. The Condition object inherits the fairness of the Lock Object. For fair locks, the thread is released from 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, await, signal, and signalAll are used with the wait, notify, and policyall methods. However, Condition extends the Object, so it also contains the wait and notify methods. Make sure the version used-await and signal.
The official usage 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();        }    }}
You can also use an actual example to explain the usage of Condition:
We need to print the 0 numbers from 1 to 9, which are printed by thread A 1-3, thread B 4-6, and thread A prints 7-9. we use Condition to demonstrate the solution:
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 Object method of wait, notify, notifyAll method to achieve this instance can refer to: http://outofmemory.cn/java/java.util.concurrent/thread-sync-with-object-wait-notify-notifyAll
It can also be expanded. ThreadA prints 123, ThreadB prints 456, and ThreadA prints 789. Then, ThreadB prints 10 11 12:
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. 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 output 10-12101112

 

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.