Java concurrent programming (1) CountDownLatch

Java Concurrent Programming (1) CountDownLatch

Blog Classification: JDK
Java Concurrent Concurrent CountDownLatch Multithreading
Introduction

CountDownLatch is a new thread auxiliary class introduced by JDK5, which is used to help developers "more accurately" control the thread state. The CountDownLatch class has a built-in lock counter, which is specified when an instance of this class is created. Each time the countDown() method is called, the number of the counter is decremented by one. When the counter is zero, all waiting threads are released and executed, otherwise These threads are in a waiting state.

This class can be used in two typical situations.

The first situation is that several threads must wait for an event or some action to occur before starting to execute. For example, Bolt and the other seven runners in the 100-meter race had to wait until the starting gun fired before they could start. When the last runner crossed the finish line, the 100-meter race was over. In this case, it needs to be initialized with parameter 1.

The second situation is when something or action must wait until all threads have finished executing. For example, when assembling a car, 4 workers assemble 4 wheels. Only after all 4 wheels are installed, the assembly line can let the car enter the next assembly stage. In this case, use parameter 4 to initialize. Of course, this situation can also be controlled with the CyclicBarrier class.

The 100- meter trapeze battle

first simulates the first situation with code. There is a lock in the Player class that keeps the player in a wait state. The athlete can start only after the starting gun is fired. The latch.await() method does exactly this. The private function of run1 in Player makes the thread sleep for a random time within 10 seconds, simulating the athlete's running process, and after the run, the athlete reaches the finish line.

In the main function, create a new CountDownLatch and set the calculator to 1. Then create a thread pool that can run 8 threads at the same time - a simulated track, and let all athletes enter the track by calling the ExecuteService.execute() function. At this time, the value of the counter is 1, and all threads are in a waiting state. OK, next, call latch.countDown() to make the lock counter zero. The 8 threads in the ExecutorService are started at the same time, and all the athletes start. Finally, the ExecutorService.shutdown() function will wait for all 8 threads in the thread pool to be executed, and then close the thread pool, --- the game is over.
Java code Collection code
class Player implements Runnable { 
    private String name; 
    private CountDownLatch latch; 
 
    public Player(String name, CountDownLatch latch) { 
        super(); 
        this.name = name; 
        this.latch = latch; 
    } 
 
    @Override 
    public void run( ) { 
        try { 
            latch.await(); 
            run1(); 
            System.out.format("Player %s reaches the endponit.%n", name); 
        } catch (InterruptedException e) { 
            // TODO Auto-generated catch block 
            e.printStackTrace(); 
        } 
    } 
 
    private void run1() throws InterruptedException { 
        Thread.sleep(new Random().nextInt(10000)); 
    } 
 
    public static void main(String args[]) { 
        CountDownLatch latch = new CountDownLatch(1); 
        ExecutorService executor = Executors.newFixedThreadPool(8); 
        String players[] = { "Bolt", "Robles", "Liu Xiang", "Johnson", "Louis", "Gatlin", "Green", "Robert" }; 
        for (int i = 0; i < 8; i++) 
            executor.execute(new Player(players[i], latch)); 
        latch.countDown(); 
        executor.shutdown(); 
    } 
}  

Assembling the wheels of the car

Suppose there are 4 workers assembling the wheels on a car at the same time on the car production line 4 wheels, because the speed at which each worker assembles the wheels will be different. Before the car enters the next operation link, the production line must know that the 4 wheels of the car have been assembled. First, set the calculator to 4. When a worker installs the wheel, press the button to decrement the counter by one, and the value of the counter becomes 3. Finally, after all 4 workers press the button, the value of the counter becomes zero. Once the counter is zero, the control program of the production line sends the car to the next assembly operation.
Let's first look at the Worker class, which represents a worker who can install a wheel. In order to clearly represent a wheel, the wheel is abstracted into a number, represented by an id. The Worker.run() method calls the marshalTyre() private member function---representing the assembly of the wheel, but it just makes the thread sleep for a random time within 60s. In fact, the method is the main business code that does the assembly of the wheel. When the worker finishes his work, call the latch.countDown() method, press the calculator button, and tell the production line control center that I have completed the task of following the wheel. Ha, I can go get a drink.

Look again at the line latch.await() in the main function, indicating that the pipeline has been waiting for the counter to be cleared. When the calculator is zero, you can count the whole time for this assembly.

Java code Collection code
public class Worker implements Runnable { 
    private int id; 
    private CountDownLatch latch; 
 
    public Worker(int id, CountDownLatch latch) { 
        this.id = id; 
        this.latch = latch; 
    } 
 
    @Override 
    public void run() { 
        try { 
            System.out.format("tyre %d is assembling.%n", id); 
            marshalTyre(); 
            System.out.format("tyre %d is assembled.%n", id); 
            latch.countDown(); 
        } catch (InterruptedException e) { 
            e.printStackTrace(); 
        } 
 
    } 
 
    private void marshalTyre() throws InterruptedException { 
        Thread.sleep(new Random().nextInt(60000)); 
    } 
 
    /**
     * @param args
     * @throws InterruptedException
     */ 
    public static void main(String[] args) throws InterruptedException { 
        CountDownLatch latch = new CountDownLatch(4); 
        ExecutorService executor = Executors.newFixedThreadPool(4); 
        long s = System.currentTimeMillis(); 
        for (int i = 0; i < 4; i++) 
            executor.execute(new Worker(i, latch)); 
        latch.await(); 
        System.out.format("the 4 tyres were assembled. costs %d ms.%n", System.currentTimeMillis() - s); 
        executor.shutdown(); 
    } 


Well, let's expand on this example. Before workers assemble the tires, the tires must have been placed in the proper position. If the tires are not ready when the car arrives, they must wait until the tires are ready. Start the installation. In other words, the tires are not ready, and the workers have been waiting for the "tire ready" event. When the tire is ready, it can be installed. In this case, two CountDownLatchs are needed. How to use it will be written next time.

[Original content, all rights reserved, if reprinted, please indicate the source, if there is any error, please point out, I would be grateful]
--- Reprinted from http://mojarra.iteye.com/blog/1259288

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326605565&siteId=291194637