Java Condition

Java has two mechanisms for blocking and wake threads

First, to achieve by Object of wait and notify combined with the synchronized keyword

Two, Condition collections Lock

This article describes the second

Condition attribute

  • Object wait and notify mechanism similar to, but different in that, Condition is a need to associate Lock objects created by newCondition Lock object ()
  • Finely control the multi-threaded, with a lock, you can create multiple Condition

    For example: a multithreaded read / write a heap buffer, producer consumer model, which thread can be clearly awakened by Condition

example

com.darchrow.test.condition Package; 

Import java.util.LinkedList; 
Import java.util.List; 
Import java.util.concurrent.CountDownLatch; 
Import java.util.concurrent.ExecutorService; 
Import java.util.concurrent.Executors; 
java.util.concurrent.locks.Condition Import; 
Import java.util.concurrent.locks.Lock; 
Import java.util.concurrent.locks.ReentrantLock; 

/ * * 
 * examples: 
 * the Add () method: when the set length 10:00, it suspends the current thread, so that other threads go first. Otherwise a message will be added, and raise it performs sub () thread 
 * sub (): When the length is 0, the operation Similarly 
 * 
 * @author MDL 
 * @date 2020/3/25 10:08 
 * / 
public  class the implements the Runnable {ConditionDemo 

    Private Finalstatic Lock lock = new ReentrantLock();

    private final static Condition addCondition = lock.newCondition();

    private final static Condition subCondition = lock.newCondition();


    private static int num = 0;

    private static List<String> list = new LinkedList<>();

    private boolean flag;

    private CountDownLatch countDwonLatch;

    public ConditionDemo(boolean flag, CountDownLatch countDwonLatch) {
        the this .flag = In Flag;
         the this .countDwonLatch = countDwonLatch; 
    } 

    Private  void the Add () {
         Lock . Lock ();
         the try {
             IF (list.size () == 10 ) {
                 // set is full, can not be combined, and Less waiting 
                the addCondition. the await (); 
            } 
            // not full, you can continue to add elements 
            NUM ++ ; 
            list.add ( " the Add Banana " + NUM); 
            . System OUT .println (" Current thread: " + Thread.currentThread () getName () +. " , Was added to the collection element, the current length of the " + list.size ());
             // add finished, can reduce the 
            subCondition.signal (); 
            countDwonLatch .countDown (); 
            the System. OUT .println ( " current thread: " . Thread.currentThread + () getName () + " countDownLatch.getCount () = " + countDwonLatch.getCount ()); 
        } the catch (Exception E) { 
            e.printStackTrace (); 
        } the finally {
             Lock.unlock (); 
        } 

    } 

    Private  void Sub () {
         Lock . Lock ();
         the try {
             IF (list.size () == 0 ) {
                 // set the empty, blocking, irreducible, waiting for 
                subCondition. the await (); 
            } 
            // have the data, can be reduced 
            num-- ; 
            String STR = List. GET ( 0 ); 
            list.remove ( 0 ); 
            the System. OUT .println ( " current thread:" . Thread.currentThread + () getName () + " , Save the collection element, " + STR + " , reducing the length of the " + list.size ());
             // Save finished, can continue to increase the 
            addCondition.signal () ; 
            countDwonLatch.countDown (); 
            the System. OUT .println ( " current thread: " . Thread.currentThread + () getName () + " countDownLatch.getCount () = " + countDwonLatch.getCount ()); 
        } the catch (Exception E ) { 
            e.printStackTrace (); 
        } the finally {
            lock.unlock();
        }


    }


    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDwonLatch = new CountDownLatch(40);
        ConditionDemo ConditionDemo1 = new ConditionDemo(true, countDwonLatch);
        ConditionDemo ConditionDemo2 = new ConditionDemo(false, countDwonLatch);
        ExecutorService executorService1 = Executors.newFixedThreadPool(10);
        ExecutorService executorService2 = Executors.newFixedThreadPool(10);

        for (int i = 0; i < 20; i++) {
            executorService1.execute(ConditionDemo1);
            executorService2.execute(ConditionDemo2);
        }
        countDwonLatch.await();
        executorService1.shutdown();
        executorService2.shutdown();

        System.out.println("最终集合元素个数:" + list.size());

//        Thread t1 = new Thread(ConditionDemo1);
//        Thread t2 = new Thread(ConditionDemo1);
//        Thread t3 = new Thread(ConditionDemo1);
//        Thread t4 = new Thread(ConditionDemo1);
//        Thread t5 = new Thread(ConditionDemo1);
//
//        Thread t6 = new Thread(ConditionDemo2);
//        Thread t7 = new Thread(ConditionDemo2);
//        Thread t8 = new Thread(ConditionDemo2);
//        Thread t9 = new Thread(ConditionDemo2);
//
//        t1.start();
//        t2.start();
//        t3.start();
//        t4.start();
//        t5.start();
//        t6.start();
//        t7.start();
//        t8.start();
//        t9.start();

    }

    @Override
    public void run() {
        if (flag) {
            add();
        } else {
            sub();
        }

    }
}

 

Guess you like

Origin www.cnblogs.com/bloodthirsty/p/12566669.html