zoukankan      html  css  js  c++  java
  • 如何保证多个线程同时启动?

    可以 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();
            }
        }
        
    }


    原文链接
     


     

  • 相关阅读:
    SAS学习 day10
    SAS学习 day9
    SAS学习 day8
    Python解释器 发展史
    os. 模块
    字典
    类型1
    计算机编码
    EDA 会议整理
    2020-8-27
  • 原文地址:https://www.cnblogs.com/ConstXiong/p/12054143.html
Copyright © 2011-2022 走看看