How to ensure that multiple threads at the same time start?

Can wait (), notify () implemented; CountDownLatch may also be used to achieve the starting gun.

CountDownLatch achieve relatively simple, as follows:

package constxiong.interview;

import java.util.concurrent.CountDownLatch;

/**
 * Test to start multiple threads
 * @author ConstXiong
 */
public class TestCountDownLatch {

    private static CountDownLatch cld = new CountDownLatch(10);
    
    public static void main(String[] args) {
        for (int i = 0; i <10; i++) {
            Thread t = new Thread(new Runnable() {
                public void run() {
                    try {
                        . CLD the await (); // thread blocking Here, all threads waiting for completion of calls start () method, performed together 
                    } the catch (InterruptedException E) {
                        e.printStackTrace ();
                    }
                    System.out.println(Thread.currentThread().getName() + ":" + System.currentTimeMillis());
                }
            });
            t.start();
            cld.countDown();
        }
    }
    
}

 


Description link
 


 

 

Guess you like

Origin www.cnblogs.com/ConstXiong/p/12054143.html
Recommended