CountDownLatch
使用:
/** * 测试同时启动多个线程 * 这里调用t.start不会立刻启动,会等到CountDownLatch域值为零才启动,所以10个线程全部是await状态。等for循环执行到最后一次后,才同时start * */ public class LockTest { public static void main(String[] args){ // 设置域值为10 CountDownLatch cdl = new CountDownLatch(10); for (int i = 0; i < 30; i++) { Thread t = new Thread(() -> { try { // 线程等待,等待到线程域值(10)为零,才启动线程 cdl.await(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()); }); t.start(); // 域值减一 cdl.countDown(); } } }
或者:
/** * 这里创建了20个线程,每个线程增加1000次, * 20个线程执行完成后再执行main线程 */ public class VolatileAtomicTest { public static void main(String[] args) throws Exception { CountDownLatch cdl = new CountDownLatch(20); Add add = new Add(); // 创建20个线程,每个线程对i增加100次 for (int i = 1; i <= 20; i++) { new Thread(()->{ for (int j = 1; j <= 1000; j++) { add.plus(); } cdl.countDown(); }).start(); } // 上面线程全部执行完成再执行主线程 cdl.await(); System.out.println(add.num); } } class Add { volatile int num = 0; public void plus() { num++; } }