The obstacle device is a kind of multithreading concurrency control method, the usage is very simple. Here's an example:
Import java.util.concurrent.BrokenBarrierException;
Import Java.util.concurrent.CyclicBarrier;
/**
* Java Threads: New features-obstacles
*
* @author Leizhimin
*/
public class Test {
public static void Main (string[] args) {
Create the obstacle and set the task to be performed for all maintask threads to reach the barrier point (Runnable)
Cyclicbarrier cb = new Cyclicbarrier (7, New Maintask ());
New SubTask ("A", CB). Start ();
New SubTask ("B", CB). Start ();
New SubTask ("C", CB). Start ();
New SubTask ("D", CB). Start ();
New SubTask ("E", CB). Start ();
New SubTask ("F", CB). Start ();
New SubTask ("G", CB). Start ();
}
}
/**
* Main Task
*/
Class Maintask implements Runnable {
public void Run () {
System.out.println (">>>> Master task executed!") <<<< ");
}
}
/**
* Sub Task
*/
Class SubTask extends Thread {
private String name;
Private Cyclicbarrier CB;
SubTask (String name, Cyclicbarrier CB) {
THIS.name = name;
THIS.CB = CB;
}
public void Run () {
System.out.println ("[subtask] + name +"] started! ");
for (int i = 0; i < 999999; i++); Simulate a time-consuming task
System.out.println ("[subtask] + name +"] started executing and notified the barrier has been completed! ");
try {
Notice the barrier is complete.
Cb.await ();
catch (Interruptedexception e) {
E.printstacktrace ();
catch (Brokenbarrierexception e) {
E.printstacktrace ();
}
}
}
Run Result:
[子任务E]开始执行了!
[子任务E]开始执行完成了,并通知障碍器已经完成!
[子任务F]开始执行了!
[子任务G]开始执行了!
[子任务F]开始执行完成了,并通知障碍器已经完成!
[子任务G]开始执行完成了,并通知障碍器已经完成!
[子任务C]开始执行了!
[子任务B]开始执行了!
[子任务C]开始执行完成了,并通知障碍器已经完成!
[子任务D]开始执行了!
[子任务A]开始执行了!
[子任务D]开始执行完成了,并通知障碍器已经完成!
[子任务B]开始执行完成了,并通知障碍器已经完成!
[子任务A]开始执行完成了,并通知障碍器已经完成!
>>>>主任务执行了!<<<<
Process finished with exit code 0
From the execution result, it can be seen that when all subtasks are completed, the main task executes and achieves the control goal.
Source: http://lavasoft.blog.51cto.com/62575/222738