In practical applications, sometimes multiple threads need to work at the same time to accomplish the same thing, and in the process of completion, they often wait for other threads to finish a certain stage before execution, after All threads reach a certain stage, they are executed in a unified manner.
For example, several tour groups need to arrive in Wuhan through Shenzhen, Guangzhou, Shaoguan, and Changsha. There are self-driving tours, hiking tours, and bus tours in the tour group. These tour groups depart at the same time, and every destination must wait for other tour groups to arrive here and start at the same time, till they all arrive at the terminal station Wuhan.
At this time, cyclicbarrier can be used. The most important attribute of javasicbarrier is the number of participants, and the most important method is await (). When await () is called by all threads, it indicates that these threads can continue to run; otherwise, they will wait.
Count
Package Test. Multithread;
Public Class Counter {
Private Int Counter;
Public Void Increment (){
Counter ++ ;
}
Public Int Value (){
Return Counter;
}
}
Custom Thread class
Package Test. Multithread;
ImportJava. util. Concurrent. javasicbarrier;
Public Class Synchedthread Extends Thread {
Private Cyclicbarrier enterbarrier;
Private Cyclicbarrier exitbarrier;
Public Synchedthread (runnable,
Cyclicbarrier enterbarrier,
Cyclicbarrier exitbarrier ){
Super (Runnable );
This . Enterbarrier = Enterbarrier;
This . Exitbarrier = Exitbarrier;
}
@ Override
Public Void Run (){
Try {
Enterbarrier. Await ();
Super . Run ();
Exitbarrier. Await ();
} Catch (Exception e ){
Throw New Runtimeexception (E );
}
}
}
Test class
Package Test. Multithread;
Import StaticOrg. JUnit. Assert. assertequals;
ImportJava. util. Concurrent. brokenbarrierexception;
ImportJava. util. Concurrent. javasicbarrier;
ImportOrg. JUnit. test;
Public Class Multithreadtest {
@ Test
Public Void Testaaa () Throws Exception {
Final Counter = New Counter ();
Final Int Numberofthreads = 20 ;
Final Int Incrementsperthread = 1000 ;
Cyclicbarrier entrybarrier = New Cyclicbarrier (numberofthreads + 1 );
Cyclicbarrier exitbarrier = New Cyclicbarrier (numberofthreads + 1 );
Runnable = New Runnable (){
Public Void Run (){
For ( Int I = 0 ; I < Incrementsperthread; I ++ ){
Counter. increment ();
}
}
};
For ( Int I = 0 ; I < Numberofthreads; I ++ ){
New Synchedthread (runnable, entrybarrier, exitbarrier). Start ();
}
Assertequals ( 0 , Counter. Value ());
Entrybarrier. Await ();
Exitbarrier. Await ();
Assertequals (numberofthreads * Incrementsperthread, counter. Value ());
}
}