[Study now sell] CountDownLatch --- realize "one can't be less" in payment-we are all very good

 
Scenario introduction:
 
When making payment in the previous project, the multi-thread method was used. Thread A is the business thread of the project. After the process is completed at a certain point,
another thread B will be opened when the payment is made. After payment , the payment is called payment Interface for payment. What we have done is that we generally know that WeChat and Alipay will call back to an interface when we pay. Here, we use CountDownLatch to wait for the results of these two threads AB to be completed. The thread A process is completed and the thread B The payment is successful, and then I proceed to the next step to generate a successful logo, and then display it on the front end. The following is a small demo to simulate this scenario:

package com.zcw.demo2;

import java.util.concurrent.CountDownLatch;

/**
 * @ClassName : MyThread
 * @Description :
 * @Author : Zhaocunwei
 * @Date: 2020-04-17 13:44
 */
public class MyThread extends Thread {
    private CountDownLatch maxRuner;
    public MyThread(CountDownLatch maxRuner){
        super();
        this.maxRuner = maxRuner;
    }
    @Override
    public void run(){
        try {
            Thread.sleep(2000);
            maxRuner.countDown();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch maxRuner = new CountDownLatch(10);
        MyThread[] tArray = new MyThread[Integer.parseInt(""+maxRuner.getCount())];
        for(int i =0;i<tArray.length;i++){
            tArray[i] = new MyThread(maxRuner);
            tArray[i].setName("线程" +(i+1));
            tArray[i].start();
        }
        maxRuner.await();
        System.out.println("都回来了!");
    }
}

operation result:

Insert picture description here
Enlightenment:
 

Through this case, we have demonstrated the blocking feature between multiple threads and synchronization points. All threads must reach the synchronization point before they can continue to run down.

Published 475 original articles · Like 16 · Visits 30,000+

Guess you like

Origin blog.csdn.net/qq_32370913/article/details/105578775
Recommended