如何保证多个线程同时启动?


可以 wait()、notify() 实现;也可以使用发令枪 CountDownLatch 实现。

CountDownLatch 实现较简单,如下:

package constxiong.interview;

import java.util.concurrent.CountDownLatch;

/**
 * 测试同时启动多个线程
 * @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.await();//将线程阻塞在此,等待所有线程都调用完start()方法,一起执行
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + ":" + System.currentTimeMillis());
                }
            });
            t.start();
            cld.countDown();
        }
    }
    
}

 


原文链接
 


 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM