CountDownLatch的高并发与顺序执行

一、高并发:

@Service
public class ConcurrentTest {

    /**
     * 线程数量
     */
    public static final int THREAD_NUM = 100;

    /**
     * 开始时间
     */
    private static long startTime = 0L;

    @PostConstruct
    public void init() {
        try {
            startTime = System.currentTimeMillis();
            System.out.println("CountDownLatch started at: " + startTime);
            // 初始化计数器为1
            CountDownLatch countDownLatch = new CountDownLatch(1);
            for (int i = 0; i < THREAD_NUM; i ++) {
                new Thread(new Run(countDownLatch)).start();
            }
            // 启动多个线程
            countDownLatch.countDown();
        } catch (Exception e) {
            System.out.println("Exception: " + e);
        }
    }

    /**
     * 线程类
     */
    private class Run implements Runnable {
        private final CountDownLatch startLatch;
        public Run(CountDownLatch startLatch) {
            this.startLatch = startLatch;
        }
        @Override
        public void run() {
            try {
                // 线程等待
                startLatch.await();
                // 执行操作
                System.out.println("当前线程:"+Thread.currentThread().getName()+"执行自己的方法");
                long endTime = System.currentTimeMillis();
                System.out.println(Thread.currentThread().getName() + " ended at: " + endTime + ", cost: " + (endTime - startTime) + " ms.");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    public static void main(String[] args) {
        ConcurrentTest test = new ConcurrentTest();
        test.init();
    }
}

 

二、顺序执行

public class Test1 {

    public static void main(String[] args) {    
        CountDownLatch c0 = new CountDownLatch(0); 
        CountDownLatch c1 = new CountDownLatch(1); 
        CountDownLatch c2 = new CountDownLatch(1); 

        Thread t1 = new Thread(new Work(c0, c1));
        //c0为0,t1可以执行。t1的计数器减1

        Thread t2 = new Thread(new Work(c1, c2));
        //t1的计数器为0时,t2才能执行。t2的计数器c2减1

        Thread t3 = new Thread(new Work(c2, c2));
        //t2的计数器c2为0时,t3才能执行

        t2.start();
        t1.start();
        t3.start();

    }
    //定义Work线程类,需要传入开始和结束的CountDownLatch参数
    static class Work implements Runnable {
        CountDownLatch c1;
        CountDownLatch c2;
        Work(CountDownLatch c1, CountDownLatch c2){
            super();
            this.c1=c1;
            this.c2=c2;
        }
        public void run() {
            try {
                c1.await();//前一线程为0才可以执行
                System.out.println("开始执行线程:"+ Thread.currentThread().getName());
                c2.countDown();//本线程计数器减少
            } catch (InterruptedException e) {              
            }  

        }
    }

}

 

你可能感兴趣的:(多线程)