可以 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(); } } }
- Java 自學指南
- Java 面試題匯總PC端瀏覽【點這里】
- Java知識圖譜
- Java 面試題匯總小程序瀏覽,掃二維碼