Synchronization tools CountDownLatch and CyclicBarrier

In the development, some asynchronous operation will significantly speed up the execution better experience, but it also increases the complexity of development, like a thread with a lot, you have to learn from these

  • Thread wait() notify() notifyall()method
  • Asynchronous thread return Future

  • ThreadLocal class
  • Thread Pool ThreadPoolExecutor
  • Synchronization tools CountDownLatch, CyclicBarrier, Semaphore, Phaser,Exchanger

Each of the above estimated 2 to 3 years for students who are the nightmare of java, more difficult to understand, this simple saying CountDownLatchandCyclicBarrier

CountDownLatch

CountDownLatch Generally more common in the implementation of a long time resolvable task, be regarded as a synchronization tool category most easily understood.

Example 1:

A simple example: a data excel 1,000,000 export data from the database needs to find out, and then outputs the encapsulated data to the front end excel.

A little analysis can know that this operation will certainly be very time-consuming, it's a bottleneck in query the database and write data on excel, if I read one every 100,000 data into a database and write excel files, and finally put all the zip package to use excel , the use of multi-threading, because the database does not read lock, there will be an order of magnitude performance improvement (there are practiced), then there will be a problem, I start multiple threads, the main thread how do you know all threads have completed it, only after all threads have completed, in order to package all excel file, then you can use CountDownLatchpseudo-code is as follows:

// Excel 线程
class ExcelThread extend Thread{
    private CountDownLatch countDownLatch;
    public ExcelThread(CountDownLatch countDownLatch){
        this.countDownLatch = countDownLatch;
    }
    public void run(){
        try{
            // do query db & write excel 
        }finally{
            countDownLatch.countDown();
        }
    }
}

public static void main(){
    //假定生成 3 个 excel 
    CountDownLatch countdownlatch = new CountDownLatch(3);
    foreach : 
    new ExcelThread(countdownlatch).start();
    
    countDownLatch.await();
    
    // do zip compress & down 
}

Example Two:

If you used the IDM download the tool, see its download progress must know that it is multi-threaded downloading, automatically divided into a number of segments, in fact, use of java RandomAccessFilewith CountDownlatchthe same can be done multi-threaded download, we can instantiate multiple RandomAccessFilethen to point to a different file file location, the data can then fill to the inside, the main thread after the file integrity test points thread completed.

Of course IDM better, it will have completed another thread, if a certain period are still stuck, then continue to separate, the same multi-threaded download, of course, speed is fast.

Example Three:

For CountDownLatch, other threads for gamers, such as the King of glory, thread the main thread to control the game began. Before all players are ready, the main thread is in a wait state, that is, the game can not start. When all the players are ready, the next step of action implementers main thread, that is to start the game.

CyclicBarrier

As compared to CountDownLatchthat in the main thread to wait, CyclicBarrierit is the child thread wait for each other, while the main thread has already ended, and while waiting for another child thread, can be attached to a CountDownLatchthread similar function, and all sub-threads have completed a re-operation, and CyclicBarrierit is reusable, so much, to see how it is used will know what it means.

Five six-legged like the game did not know the reader played, each player is a thread must wait for each other before they can be ready for the next step, which can also be a commander he waited until all the students after the completion of preparation issued instructions, left foot, right foot. . . Pseudo-code as follows:

// 游戏玩家线程
class GamePerson extend Thread{
    private CyclicBarrier cyclicBarrier;
    public GamePerson(CyclicBarrier cyclicBarrier){
        this.cyclicBarrier = cyclicBarrier;
    }
    public void run(){
        // 走下一步的准备阶段
        prepareNextStep();
        cyclicBarrier.await(); 
        // 走下一步
        nextStep();
    }
}

// 主线程
public static void main(){
    CyclicBarrier cyclicBarrier = new CyclicBarrier(5);
    //构建  5 个游戏玩家
    foreach:
    new GamePerson(cyclicBarrier);
    
    // 游戏开始,并开始计时
    startGame();beginCountTime();
    
    foreach:gamepersons
        gameperson.start();
}

// 主线程,添加指挥员
class Leader extend Thread{
    public void run(){
        System.out.println(“开始走”);
    }
}
// 主线程
public static void main(){
    CyclicBarrier cyclicBarrier = new CyclicBarrier(5,new Leader());
    //构建  5 个游戏玩家
    foreach:
    new GamePerson(cyclicBarrier);
    
    // 游戏开始,并开始计时
    startGame();beginCountTime();
    
    foreach:gamepersons
        gameperson.start();
}

// 前面的例子只能跨一步,如果需要重用 CyclicBarrier 需要把主线程也当做同步对象,代码如下 
public static void main(){
    CyclicBarrier cyclicBarrier = new CyclicBarrier(6);
    //构建  5 个游戏玩家
    foreach:
    new GamePerson(cyclicBarrier);
    
    // 游戏开始,并开始计时
    startGame();beginCountTime();
   
    //假设让它们走 10 步
    for(int i=0;i<10;i++){
        cyclicBarrier.reset();
     foreach:gamepersons
        gameperson.start();
     cyclicBarrier.await();
   }
}

Little promotion

Writing is not easy, I hope the support of open source software, and my gadgets, welcome to gitee point star, fork, put bug.

Excel common import and export, support Excel formulas
blog address: https://blog.csdn.net/sanri1993/article/details/100601578
gitee: https://gitee.com/sanri/sanri-excel-poi

Use the template code, the gadget generate code from the database, and some projects can often be used in the
blog address: https://blog.csdn.net/sanri1993/article/details/98664034
gitee: https://gitee.com/ sanri / sanri-tools-maven

Guess you like

Origin www.cnblogs.com/sanri1993/p/11980185.html