7. Condition controls thread communication

  • The Condition interface describes the Condition variables that may be associated with the lock. These variables are similar in usage to implicit monitors accessed using Object.wait, but provide more power. In particular, a single Lock can be associated with multiple Condition objects. To avoid compatibility issues, the Condition method has a different name than the corresponding Object version.

  • In Condition, the corresponding methods to wait, notify, and notifyAll are await, signal, and signalAll, respectively.

  • The Condition instance is essentially bound to a lock. To get a Condition instance for a particular Lock instance, use its newCondition() method.

class Clerk {
    private int product = 0;
    / * * * * / lock
    private Lock lock = new ReentrantLock();

    /** * control thread communication */
    private Condition condition = lock.newCondition();

    /** ** */
    public void get(a) {
        lock.lock();
        try {
            while (product >= 1) {
                System.out.println("The product is full");
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName() + ":" + ++product);
            condition.signalAll();
        } finally{ lock.unlock(); }}/** ** sell goods */
    public void sale(a) {
        lock.lock();
        try {
            while (product <= 0) {
                System.out.println("Shortage");
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName() + ":" + --product);
            condition.signalAll();
        } finally{ lock.unlock(); }}}Copy the code