Java multi-threaded series of locking (Latch) and fencing (CyclicBarrier)

Today encounter a problem on multi-threaded task item, what about graphic description:

1. The front end of the need for timely return mission status

2. Open a background thread to perform a specific task of business, the business consists of four parts, four parts completed is not complete

3. Business in some time-consuming or require multi-threaded task alone has opened a thread pool

4. As the main tasks and subtasks thread pool threads are running in parallel, how do you know when to thread the entire business will be completed?

 

Well, I thought at first task is to give each child thread business plus a mark, the other from a listener thread when the task starts to begin listening if all traffic marker has reached completion status, if all the subtasks mark complete, is considered mission completed.

Is no problem on the service implementation. Just open a separate thread of this operation is still a little show, and get maintenance subtasks mark. True not very convenient

Here recently seen the usage of multi-threaded bolt when it is viewed, and instantly feel a wave of routines can be applied

General realization becomes a sub-task thread pool task bolt lock, when the bolt open before subsequent task, when the last child to complete a task, the task can be completed.

Is not it a lot easier, save a lot of business and mark tasks listening thread.

 

Good then the rest of the space we have to look at the basic usage of a bolt

1. The latch (Latch)

Latch (Latch) - to ensure that multiple threads after the completion of each transaction, will continue to open the contents of the back, or else have been waiting for.

Counter latch (CountDownLatch) - is JDK5 + latch inside of an implementation that allows one or more threads wait for an event to occur. CountDownLatch counter has a positive number, the countDown ();  counter subtraction operation, the await (); wait counter = 0. All await the thread will block until the counter is 0 or interruption or timeout waiting threads.

Mainly two methods: CountDown Methods and Await Save lock bolt and keeper is waiting.

public static void main(String[] args) throws InterruptedException {
        // declare, wait five times the number of events
        CountDownLatch await = new CountDownLatch(5);
 
        // Create and start turn in a waiting state 5 MyRunnable threads
        for (int i = 1; i < 6; ++i) {
            new Thread(new MyRunnable(await, i)).start();
        }
 
        System.out.println ( "waiting thread to start work ......");
        await.await();
        System.out.println ( "End!");
}

 Flow Description

 

 

 

 

 By the way here to find out the fence, and a bolt similar operations, although not yet encountered this kind of business scenarios

 2. Fences (CyclicBarrier)

Fence similar to the lockout, it blocked a set of threads until an event occurs. The key difference between the fence and the lockout is that all threads must arrive at the same location of the fence, in order to continue. Lockout wait for the event, and the fence waiting for the other thread.

Roughly meaning: a business needs to do in several threads, but some details of a sub-task thread to wait for other tasks are completed to the fence after the specified location in order to continue the implementation of the future. The following example is taken from the Internet, although not very image of the flow chart may look

Scene:  such an ABC three chair, chair legs A do, B do chair surface, do propoxy chair back. 3 people are made after, it can be assembled into a chair. This is a parallel iterative, a problem into many sub-problems, when after a series of sub-issues are resolved (all child threads have questions await ();), this time the fence is open, all sub-problems thread is released, The location of the fence can keep the next use.

Examples are as follows:

public static void main(String[] args) throws InterruptedException {
    // declare, three times the number of threads waiting
    CyclicBarrier cyclicBarrier = new CyclicBarrier(3);

    // Create and start turn in a waiting state 3 MyRunnable2 threads
    new Thread(new ChairRunnable(cyclicBarrier, "椅子腿")).start();
    new Thread(new ChairRunnable(cyclicBarrier, "椅子面")).start();
    new Thread(new ChairRunnable(cyclicBarrier, "椅子背")).start();
}

  

public static class ChairRunnable implements Runnable {
    private final CyclicBarrier cyclicBarrier;
    private final String event;

    public ChairRunnable(CyclicBarrier cyclicBarrier, String event) {
        this.cyclicBarrier = cyclicBarrier;
        this.event = event;
    }

    public void run() {
        try {
            System.out.println ( "start doing [" + event + "].");
            Thread.sleep(new Random().nextInt(10000));
            cyclicBarrier.await (); // wait for other threads to finish
        } catch (InterruptedException e) {
            e.printStackTrace ();
        } catch (BrokenBarrierException e) {
            e.printStackTrace ();
        }
        System.out.println ( "[" + event + "] well, we have to assemble it together!");
    }
}

  

operation result:
[Started] the chair legs.
[Back] started chairs.
Start doing [of] the chair.
Chair [of] good, and we assemble it together!
[] Chair legs well, we assemble it together!
[Back] chair ready, we assemble it together!

  Process is as follows:

 

Guess you like

Origin www.cnblogs.com/hnusthuyanhua/p/12518900.html