通过CountDownLatch工具类,模拟高并发

package com.cdy.wx.thread;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service
public class CountDownLatchDemo {
    Logger logger = LoggerFactory.getLogger(getClass());
    
    public  void demo(){
        CountDownLatch startGate = new CountDownLatch(1);
        CountDownLatch latch = new CountDownLatch(20);
        Runnable runnable = () -> {
           try{
               startGate.await();
               System.out.println("**************************线程开始**************************");
               try {
                   Thread.sleep(2000);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
               getLock();
               System.out.println("**************************线程结束**************************");
           }catch (Exception e) {
               e.printStackTrace();
           }finally {

               latch.countDown();
           }
        };

        ExecutorService executorService = Executors.newFixedThreadPool(20);
        for(int j=0;j<20;j++){
            executorService.submit(runnable);
        }
        System.out.println("===============================");
        try {
            startGate.countDown();
            //当所有线程完成后,才继续往下执行,阻塞作用
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        executorService.shutdown();
    }
    public void getLock(){
       
        System.out.println("发送请求");
    }
    public static void main(String[] args) {
    }
}

 

你可能感兴趣的:(java)