如何保證多個線程同時啟動?


可以 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