[Java concurrent programming] 22nd: New Features of concurrency-barrier (including code)

Source: Internet
Author: User

Import java. util. concurrent. brokenBarrierException; import java. util. concurrent. cyclicBarrier; public class javasicbarriertest {public static void main (String [] args) {// create the javasicbarrier object, // and set the concurrent tasks for executing a group of five threads, execute the MainTask task CyclicBarrier cb = new CyclicBarrier (5, 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 () ;}/ *** last executed task */class MainTask implements Runnable {public void run () {System. out. println ("...... finally, we have to execute the final task ...... ") ;}}/*** a set of concurrent tasks */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 ("[concurrent task" + name + "] Start execution"); for (int I = 0; I <999999; I ++ ); // simulate the time-consuming task System. out. println ("[concurrent task" + name + "] After execution is completed, the notification barrier"); try {// notify the barrier cb every time a task is executed. await ();} catch (InterruptedException e) {e. printStackTrace ();} catch (BrokenBarrierException e) {e. printStackTrace ();}}}
The result of an execution is as follows:

[Concurrent Task B] Start execution
[Concurrent task D] Start execution
[Concurrent task E] Start execution
[Concurrent task A] Notification barrier after execution is completed
[Concurrent task E] Notification barrier after execution is completed
[Concurrent task D] Notification barrier after execution is completed
[Concurrent task C] Start execution
[Concurrent Task B] Notification barrier after execution is completed
[Concurrent task C] Notification barrier after execution is completed
... The final task is finally to be executed ......


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.