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:
- Normal instantiation: CyclicBarrier sCyclicBarrier = new CyclicBarrier (3);
- With instantiation of runnable, when the barrier is broken, Runnable is executed first: CyclicBarrier sCyclicBarrier = new CyclicBarrier (3, new Runnable () {// todo});
- await线程:sCyclicBarrier.await();
- When the number of wait threads is the count value. Wake up all waiting threads.
Principle: explained directly with source code here (subsequent supplement)
- The lock is ReentrantLock reentrant lock. ReentrantLock lock = new ReentrantLock ()
- Acquire the condition instance of the lock. Condition trip = lock.newCondition ()
- wait thread, use Condition.await
- signal thread, using Condition.signalAll
- Two constructors, initialize the party value, count value, and Runnable (runnable is executed first when waking up)
- The count value is used to calculate the number of threads. Every time a thread executes the await method, --count. Until count == 0
- await method, including whether to timeout, and timeout time
- 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.
- The for loop in dowait is for the logic of the timeout operation.
- The normal jump out of the for loop is through the dowait method (nextGeneration () re-instantiates the generation)
- breakBarrier () breaks the barrier and wakes up all wait threads
- nextGeneration () updates the status and wakes up all wait threads
- reset () resets the state. It calls breakBarrier () and nextGeneration ()