Java Concurrency Programming--cyclicbarrier

Source: Internet
Author: User

Cyclicbarrier is a synchronous helper class that allows a set of threads to wait for each other until a common barrier point (common barrier points) is reached. In programs that involve a set of fixed-size threads, these threads have to wait for each other, and cyclicbarrier is useful at this time. Because the barrier can be reused after releasing the waiting thread, it is called a cyclic barrier. Cyclicbarrier supports an optional Runnable command that runs only once at each barrier point after the last thread in a set of threads arrives (but before releasing all threads). This barrier operation is useful if you update the shared state before continuing with all participating threads.

Business Requirements

A large task often allocates a lot of subtasks to perform, and only when all subtasks are completed can the Executive Director be executed. For example, in the test system of the extraction logic, the problem is a large-scale task, including the extraction of various types of questions, such as: single-choice, multi-choice, translation problems, listening problems. All the questions can be exhausted to continue execution. According to the way we used to write code: first to extract a single topic, and then draw a number of topics, and then draw a translation problem, and then draw the listening questions, assuming that each time to draw a question is 1s, then complete a pumping problem needs 4s of time, obviously the utilization of computer resources has not reached the optimal. So how do we improve performance? Assuming that we are a 4-core CPU, we can draw a selection of topics at the same time to draw multiple choice, translation and listening problems, so the equivalent is to perform multiple tasks in parallel, then the time required to complete the problem is 1s.

Implement

With the above requirements, then we come to realize, how to draw questions.

To draw a single choice of topic Category:

/** * Radio * * @author Kang Lixian * * May 19, 2015 */public class Singleselect implements Runnable {private Resutl Resul t;private cyclicbarrier barrier;private int number;public singleselect (resutl result,cyclicbarrier barrier,int number) {this.result = Result;this.barrier=barrier;this.number=number;} Public Singleselect (resutl result,int number) {this.result = Result;this.number=number;} @Overridepublic void Run () {//system.out.println ("radio = =" +number+ "times = = Draw title = = = Start ... "); Result.setsingleselect (" Single-choice ... +number); try {//Sleep 5s//thread.sleep ((int) (Math.random () * 1000)); SYSTEM.OUT.PRINTLN ("Radio = =" +number+ "times = = Draw the title = = = End ... "); barrier.await ();} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} catch (Brokenbarrierexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}} public void Singleexam () {//system.out.println ("radio = =" +number+ "times = = Draw title = = = Start ... "); Result.setsingleselect (" Single-choice ... "+number); SYSTEM.OUT.PRINTLN ("Radio = =" +number+ "times = = Draw the title = = = End ... ");}}

The class of multi-selection, translation and hearing is similar to the above, which is omitted here.

class for storing the result of the drawing problem --- Result.java

/** * Storage of extracted questions * @author Kang Lixian * * May 19, 2015 */public class Resutl {private string Singleselect;private string Doublese Lect;private string Translate;private string Listening;public string Getsingleselect () {return singleselect;} public void Setsingleselect (String singleselect) {this.singleselect = Singleselect;} Public String Getdoubleselect () {return doubleselect;} public void Setdoubleselect (String doubleselect) {this.doubleselect = Doubleselect;} Public String Gettranslate () {return translate;} public void Settranslate (String translate) {this.translate = translate;} Public String getlistening () {return listening;} public void setlistening (String listening) {this.listening = listening;}}

combined extraction result class: --- Combine.java

public class Combine implements Runnable{private resutl result;public Combine (resutl result) {This.result=result;} @Overridepublic synchronized  void  run () {//synchronized (this) {System.out.println ("All of the draw questions completed"); System.out.println (Result.getdoubleselect ()); System.out.println (Result.getsingleselect ()); System.out.println (Result.gettranslate ()); System.out.println (Result.getlistening ());}}

Client:

public class Exam3pool {//Current performance better way public static void main (string[] args) {//Get server CPU number int cpunum = Runtime.getruntime ( ). Availableprocessors (); System.out.println ("Number of CPUs:" + cpunum);//The appropriate number of threads is the number of CPUs executorservice pool = Executors.newfixedthreadpool (Cpunum); for (int i=0;i<200000;i++) {resutl result=new resutl (); Combine combine=new Combine (result); Cyclicbarrier barrier=new cyclicbarrier (4,combine);D oubleselect doubleselect=new doubleselect (result,barrier,i); Linstening listening=new linstening (result,barrier,i); Singleselect singleselect=new Singleselect (result,barrier,i); Translate translate=new Translate (result,barrier,i);//multi-choice thread thdouble=new thread (doubleselect);//Listening problem thread Thlisten=new thread (listening);//radio Problem thread thsingle=new thread (singleselect);//translation Draw thread Thtranslate=new thread ( Translate);p Ool.execute (thdouble);p Ool.execute (Thlisten);p Ool.execute (thsingle);p Ool.execute (thtranslate);} Pool.shutdown (); System.out.println ("Main thread end ...");//20S//21 Threads}}

Summarize:

By setting the public barrier point, we can synchronize the threads and perform the following functions after the synchronization is completed, such as 5 subtasks required to perform a task, so that the remaining task threads must wait and no longer execute if one of the subtasks is not completed. Let's consider that if a subtask takes a long time, then the entire task execution time depends on the child task for the longest time, and the other subtask threads are completely waiting so that the resources are not well utilized, so can the sub-threads that have completed the task perform other tasks before waiting for the other subtasks to be completed? So that the resources can be more fully exploited? The answer is certain, the next blog we will solve this problem, please expect ~ ~ ~


Java Concurrency Programming--cyclicbarrier

Related Article

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.