Condition: realize one-to-one alternate printing of producers and consumers

Keywords: Java

The producer thread prints a statement in the set () method
Consumer thread prints a statement in the get () method
(the two print statements alternate.)
. . . .

Instance code:

package test.Thread4;


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

class MyService5{
    private ReentrantLock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();
    private boolean hasValue = false;

    public void set()   {
        System.err.println("Into the producer approach");
        try{
            lock.lock();
            while (hasValue == true){
                condition.await();
            }
            System.out.println("Produce a product");
            hasValue = true;
            condition.signal();
        }catch (InterruptedException e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public void get(){
        System.err.println("Into the consumer approach");
        try {
            lock.lock();
            while (hasValue == false){
                condition.await();
            }
            System.out.println("Consume a product");
            hasValue = false;
            condition.signal();
        }catch (InterruptedException e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}

class MyThreadA extends Thread{
    private MyService5 service5;

    public MyThreadA(MyService5 service5) {
        this.service5 = service5;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            service5.set();
        }
    }
}



class MyThreadB extends Thread{
    private MyService5 service5;

    public MyThreadB(MyService5 service5) {
        this.service5 = service5;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            service5.get();
        }
    }
}


public class ConditionTest3 {
    public static void main(String[] args) {
        MyService5 myService5 = new MyService5();
        MyThreadA a = new MyThreadA(myService5);
        a.start();
        MyThreadB b = new MyThreadB(myService5);
        b.start();
    }
}

Operation result:

Into the consumer approach
Into the producer approach
Produce a product
Consume a product
Into the consumer approach
Into the producer approach
Produce a product
Into the producer approach
Consume a product
Into the consumer approach
Produce a product
Into the producer approach
Consume a product
Into the consumer approach
Produce a product
Into the producer approach
Consume a product
Into the consumer approach
Produce a product
Into the producer approach
. . . . . .

Posted by lore_lanu on Sat, 02 May 2020 23:29:40 -0700