Usage analysis of Cyclicbarrier in Java _java

Source: Internet
Author: User

Copy Code code as follows:

public class Testcyclicbarrier {

private static final int thread_num = 5;

public static class Workerthread implements runnable{

Cyclicbarrier barrier;

Public Workerthread (Cyclicbarrier b) {
This.barrier = b;
}

@Override
public void Run () {
TODO auto-generated Method Stub
try{
System.out.println ("Worker ' s Waiting");
The thread waits here until all the threads have reached barrier.
Barrier.await ();
System.out.println ("ID:" +thread.currentthread (). GetId () + "Working");
}catch (Exception e) {
E.printstacktrace ();
}
}

}

/**
* @param args
*/
public static void Main (string[] args) {
TODO auto-generated Method Stub
Cyclicbarrier cb = new Cyclicbarrier (Thread_num, New Runnable () {
Executes when all threads arrive at barrier
@Override
public void Run () {
TODO auto-generated Method Stub
System.out.println ("Inside Barrier");

}
});

for (int i=0;i<thread_num;i++) {
New Thread (New Workerthread (CB)). Start ();
}
}

}
/*
Here is the output:
Worker ' s waiting
Worker ' s waiting
Worker ' s waiting
Worker ' s waiting
Worker ' s waiting
Inside Barrier
Id:12 Working
Id:8 Working
Id:11 Working
Id:9 Working
Id:10 Working
*/

1. Cyclicbarrier a number when initialized, and then calculates the number of threads that called cyclicbarrier.await () into the wait. When the number of threads reaches this amount, all threads that enter the wait state are awakened and continue.
2. Cyclicbarrier, like the meaning of its name, can be seen as an obstacle, and all threads must come together to pass through this barrier.
3. The cyclicbarrier can also be initialized with a runnable parameter, which is executed before all other threads are awakened, after the number of Cyclicbarrier is reached.

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.