Java javasicbarrier Usage Analysis, javacyclicbarrier

Source: Internet
Author: User

Java javasicbarrier Usage Analysis, javacyclicbarrier

Copy codeThe Code is 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 threads reach 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 (){
// Execute when all threads reach 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 ();
}
}

}
/*
The following 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. Define a number for javasicbarrier initialization, and then calculate the number of threads that call javasicbarrier. await () to enter the waiting state. When the number of threads reaches this value, all threads that enter the waiting state are awakened and continue.
2. javasicbarrier, like its name, can be seen as a barrier. All threads must be completed before they can pass the barrier together.
3. CyclicBarrier can also contain a Runnable parameter at the beginning. After the number of javasicbarrier tasks reaches, all other threads are executed before being awakened.

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.