Java geek

Related reading:

Java Concurrent programming (1) Knowledge map Java concurrent programming (2) Atomic Java concurrent programming (3) Visibility Java concurrent programming (4) Sequential Java concurrent programming (5) Introduction to Creating threads Java concurrent programming (6) Synchronized usage Java Concurrency programming Introduction (7) Easy to understand wait and Notify and use scenarios Java concurrency programming Introduction (8) Thread lifecycle Java concurrency programming Introduction (9) Deadlock and deadlock bit Java concurrency programming Introduction (10) lock optimization Introduction to Concurrent Programming in Java (11) Flow limiting scenarios and Spring Flow Limiting scenarios Introduction to Concurrent programming in Java (12) Producer and Consumer Patterns – Introduction to Concurrent programming in Java with code templates (13) Read/write lock and cache templates (14) CountDownLatch application scenarios Introduction to Concurrent programming in Java (16) seconds to understand the difference between the thread pool Java Concurrent programming introduction (17) one picture master common classes and interfaces for threads Java concurrent programming introduction (18) Again on thread safety Java concurrent programming introduction (19) Asynchronous task scheduling tool CompleteFeature Java Concurrent programming introduction (20) Common locking scenarios and locking tools


I. Application scenarios

In real life, there are many such scenarios: before F, it is necessary to wait for A,B,C,D and E to be completed; A,B,C,D and E can be completed concurrently, without any specific order; and after F is finished, it is necessary to start again. For example, tires, doors and car bodies need to be produced before assembling cars. The features of this scene are:

1. There are N things to do before assembling a car.

2. Everything can be processed in parallel, in no order, thus increasing efficiency.

3. Assemble one car and move on to the next. (Now, of course, all the parts are made in batches, not individually, let’s say in a limited edition Bentley built by hand.)

Around building a car, the whole process is as follows:


B, Show me code

The code class structure is as follows:

I, MakeCarBody. Java

public class MakeCarBody implements Runnable {

    private CyclicBarrier cyclicBarrier;

    public MakeCarBody(CyclicBarrier cyclicBarrier) {
        this.cyclicBarrier = cyclicBarrier;
    }

    public void run(a) {
        exec();
    }

    /** ** /
    private void exec(a) {
        // Move on to the next one
        while(true) {
            try {
                System.out.println("Start making car body...");

                long millis = ((int) (1 + Math.random() * (5 - 1 + 1))) * 1000;
                TimeUnit.MILLISECONDS.sleep(millis);
                System.out.println("Making car body is finished.");

                // Wait for other parts to be built
                this.cyclicBarrier.await();

            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch(BrokenBarrierException e) { e.printStackTrace(); }}}}Copy the code

II, MakeCarDoor. Java

public class MakeCarDoor implements Runnable {

    private CyclicBarrier cyclicBarrier;

    public MakeCarDoor(CyclicBarrier cyclicBarrier) {
        this.cyclicBarrier = cyclicBarrier;
    }

    public void run(a) {
        exec();
    }

    /** ** */
    private void exec(a) {
        // Move on to the next one
        while(true) {
            try {
                System.out.println("Start making car door...");

                long millis = ((int) (1 + Math.random() * (5 - 1 + 1))) * 1000;
                TimeUnit.MILLISECONDS.sleep(millis);
                System.out.println("Making car door is finished.");

                // Wait for other parts to be built
                this.cyclicBarrier.await();

            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch(BrokenBarrierException e) { e.printStackTrace(); }}}}Copy the code

III, MakeTire. Java

public class MakeTire implements Runnable {

    private CyclicBarrier cyclicBarrier;

    public MakeTire(CyclicBarrier cyclicBarrier) {
        this.cyclicBarrier = cyclicBarrier;
    }

    public void run(a) {
        exec();
    }

    /** ** /
    private void exec(a) {
        // Move on to the next one
        while(true) {
            try {
                System.out.println("Start making tire...");

                long millis = ((int) (1 + Math.random() * (5 - 1 + 1))) * 1000;
                TimeUnit.MILLISECONDS.sleep(millis);
                System.out.println("Making tire is finished.");

                // Wait for other parts to be built
                this.cyclicBarrier.await();

            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch(BrokenBarrierException e) { e.printStackTrace(); }}}}Copy the code

IV, AssembleCar. Java

public class AssembleCar implements Runnable {

    public void run(a) {
        try {
            System.out.println("Start assemble car...");

            //
            long millis = ((int) (1+Math.random()*(5-1+1))) * 1000;
            TimeUnit.MILLISECONDS.sleep(millis);
            System.out.println("Making assemble care is finished.");
        }
        catch(InterruptedException e) { e.printStackTrace(); }}}Copy the code

V, CyclicBarrierTest. Java

public class CyclicBarrierTest {
    public static void main(String[] args) {
        // There are three parts to build and then assemble the car
        CyclicBarrier cyclicBarrier = new CyclicBarrier(3.new AssembleCar());

        Thread makeCarBody = new Thread(new MakeCarBody(cyclicBarrier));
        Thread makeCarDoor = new Thread(new MakeCarDoor(cyclicBarrier));
        Thread makeTire = new Thread(newMakeTire(cyclicBarrier)); makeCarBody.start(); makeCarDoor.start(); makeTire.start(); }}Copy the code

Output log:

Start making car door...
Start making tire...
Start making car body...
Making tire is finished.
Making car door is finished.
Making car body is finished.
Start assemble car...
Making assemble care is finished.
Start making car body...
Start making tire...
Start making car door...
Making car body is finished.
Making tire is finished.
Making car door is finished.
Start assemble car...
Making assemble care is finished.
Copy the code

As you can see, cyclicbarriers can be used as follows:

1. The CyclicBarrier constructor takes two arguments. The first argument declares how many parts need to be built (how many things can be done in parallel) and the second argument is a Runnable, which represents the last thing to be done after the parallel.

2. After each component is finished, call the await() method of CyclicBarrier and wait for the next round to start.

3. The implementation class of Runnable passed in the CyclicBarrier constructor is automatically called when the last part is finished.

4. The Runnable implementation class completes and restarts the next round.

Third, summary

CyclicBarrier is applicable to:

1. Do a few things before you start another one.

2. Several things that need to be done can be done independently and in parallel.

3. Proceed to the next round after completing the above tasks.

end.


<– Read the mark, left like!