Fences are similar to latching, but they are different.
1. The latch is used to wait for the event, and the fence is used to wait for the other threads. What do you mean? The event that the lock is used to wait is the countdown event, which is only possible if the thread that was waiting before execution of the countdown event is likely to continue; And the fence has no similar Countdown event control thread execution, only the thread's await method can control the waiting thread execution.
2.CyclicBarrier emphasis on the n threads, everyone waiting for each other, as long as there is not finished, everyone has to wait.
Scene Analysis: 10 people go to spring outing, the stipulation reaches a place to move forward. The code is as follows
Copy Code code as follows:
Import java.util.concurrent.BrokenBarrierException;
Import Java.util.concurrent.CyclicBarrier;
Class Cyclicbarrierworker implements Runnable {
private int id;
Private Cyclicbarrier barrier;
public cyclicbarrierworker (int ID, final cyclicbarrier barrier) {
This.id = ID;
This.barrier = barrier;
}
@Override
public void Run () {
TODO auto-generated Method Stub
try {
System.out.println (id + "th people wait");
Barrier.await (); Everybody wait for the last thread to arrive
catch (Interruptedexception | Brokenbarrierexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
}
public class Testcyclicbarrier {
public static void Main (string[] args) {
int num = 10;
Cyclicbarrier barrier = new Cyclicbarrier (num, new Runnable () {
@Override
public void Run () {
TODO auto-generated Method Stub
System.out.println ("Go on together!");
}
});
for (int i = 1; I <= num; i++) {
New Thread (New Cyclicbarrierworker (I, Barrier)). Start ();
}
}
}
Output
Copy Code code as follows:
1st people wait
2nd people wait
3rd people wait
4th people wait
5th people wait
7th people wait
8th people wait
6th people wait
9th people wait
Ten th people wait
Go on together!