CyclicBarriar of Java Concurrent Components 2

scenes to be used:

Multiple threads wait for each other until they can meet the conditions before they can perform subsequent operations. CyclicBarrier describes the relationship of waiting between each thread.

Steps for usage:

  1. Normal instantiation: CyclicBarrier sCyclicBarrier = new CyclicBarrier (3);
  2. With instantiation of runnable, when the barrier is broken, Runnable is executed first: CyclicBarrier sCyclicBarrier = new CyclicBarrier (3, new Runnable () {// todo});
  3. await线程:sCyclicBarrier.await();
  4. When the number of wait threads is the count value. Wake up all waiting threads.

Principle: explained directly with source code here (subsequent supplement)

  1. The lock is ReentrantLock reentrant lock. ReentrantLock lock = new ReentrantLock ()
  2. Acquire the condition instance of the lock. Condition trip = lock.newCondition ()
  3. wait thread, use Condition.await
  4. signal thread, using Condition.signalAll
  5. Two constructors, initialize the party value, count value, and Runnable (runnable is executed first when waking up)
  6. The count value is used to calculate the number of threads. Every time a thread executes the await method, --count. Until count == 0
  7. await method, including whether to timeout, and timeout time
  8. dowait is the main logic code of thread wait. When count == 0, the wake-up operation is performed. When it is not 0, enter the for loop and execute Condition.await.
  9. The for loop in dowait is for the logic of the timeout operation.
  10. The normal jump out of the for loop is through the dowait method (nextGeneration () re-instantiates the generation)
  11. breakBarrier () breaks the barrier and wakes up all wait threads
  12. nextGeneration () updates the status and wakes up all wait threads
  13. reset () resets the state. It calls breakBarrier () and nextGeneration ()

 

Guess you like

Origin www.cnblogs.com/Courage129/p/12725400.html