Use CountDownLatch to simulate threads executing code concurrently

Use CountDownLatch to simulate thread concurrent execution code, the sample code is as follows:

package com.gaopeng.multithread;

import java.util.concurrent.CountDownLatch;

/**
 * Use CountDownLatch to simulate threads executing code concurrently
 * 
 * @author gaopeng
 *
 */
public class CountDownLatchConTest {

    // Concurrent number 
    private  static  final  int THREAD_NUM = 10 ;

    private static volatile CountDownLatch countDownLatch = new CountDownLatch(THREAD_NUM);

    public static void main(String[] args) throws InterruptedException {

        for (int i = 0; i < THREAD_NUM; i++) {
            Thread thread = new Thread(new Runnable() {

                @Override
                public  void run () {
                     // All threads wait here 
                    try {
                        countDownLatch.await();
                        System.out.println(Thread.currentThread() + " = " + System.currentTimeMillis());
                    } catch (InterruptedException e) {
                        e.printStackTrace ();
                    }

                }
            });

            thread.start();

            // After starting, the countdown counter decrements by one, indicating that a thread is ready to 
            countDownLatch.countDown ();
        }
    }
}

The results are as follows:

Thread[Thread-2,5,main] = 1587356721613
Thread[Thread-1,5,main] = 1587356721613
Thread[Thread-8,5,main] = 1587356721613
Thread[Thread-3,5,main] = 1587356721613
Thread[Thread-7,5,main] = 1587356721613
Thread[Thread-6,5,main] = 1587356721613
Thread[Thread-5,5,main] = 1587356721613
Thread[Thread-0,5,main] = 1587356721613
Thread[Thread-4,5,main] = 1587356721613
Thread[Thread-9,5,main] = 1587356721613

Guess you like

Origin www.cnblogs.com/gaopengpy/p/12737013.html