CountDownLatch 与CyclicBarrier

CountDownLatch

jdk and contract counter counts to achieve synchronization.

When using the thread pool, because the thread will not be destroyed, so use join unable to block the thread.

// Create two threads in a thread pool
Executor Executor = 
  Executors.newFixedThreadPool (2);
the while (there is not reconciliation orders) {
  // counter is initialized to 2
  CountDownLatch LATCH = 
    new new CountDownLatch (2);
  // query unreconciled orders
  Executor.execute (() -> {
    POS = getPOrders ();
    latch.countDown ();
  });
  // single query delivered
  Executor.execute (() -> {
    DOS = getDOrders ();
    latch.countDown ();
  });
  
  // wait for the end of the two query
  latch.await ();
  
  // perform reconciliation operation
  the diff = Check (POS, DOS);
  // write difference libraries difference
  Save (the diff);
}
 

CyclicBarrier processing unison

// order queue
the Vector <P> POS;
// single delivery queue
the Vector <D> DOS;
// callback thread pool 
the Executor Executor = 
  Executors.newFixedThreadPool (. 1);
Final Barrier a CyclicBarrier =
  new new a CyclicBarrier (2, () - > {
    Executor.execute (() -> Check ());
  });
  
void Check () {
  P = P pos.remove (0);
  D = D dos.remove (0);
  // perform reconciliation operations
  diff Check = (P, D);
  // write difference libraries difference
  Save (the diff);
}
  
void checkAll () {
  // cycle of inquiry order store
  the Thread the Thread new new Tl = (() -> {
    the while (line exists unreconciled ) {
      // query order store
      pos.add (getPOrders ());
      // wait
      barrier.await ();
    }
  });
  T1.start ();  
  // cyclic query library waybill
  the Thread new new the Thread T2 = (() -> {
    the while (line exists unreconciled) {
      // query waybill library
      dos.add (getDOrders ());
      // wait
      barrier.await ();
    }
  });
  T2.start ();
}
 

Published 23 original articles · won praise 19 · views 1416

Guess you like

Origin blog.csdn.net/u012335601/article/details/89606940