CountDownLatchDemo
1648 ワード
package com.smart.thread;
import java.util.Date; import java.util.concurrent.CountDownLatch;
/** Javaマルチスレッドプログラミングでは、あるスレッドが1つ以上のスレッド操作の終了(または何らかの状態に達する)を待ってから実行を開始するシーンがよく見られます. 例えば、同時テストツールを開発する場合、プライマリ・スレッドは、すべてのテスト・スレッドが完了するまで統計を開始するのにかかる時間を待つ必要があります. はこの時点でCountDownLatchによって簡単に実現できる. Created by jinxiaoyu on 17/4/11. */public class CountDownLatchDemo { public static void main(String[] args) throws InterruptedException { int totalThread = 3; long start = System.currentTimeMillis(); final CountDownLatch countDown = new CountDownLatch(totalThread); for(int i = 0; i < totalThread; i++) { final String threadName = "Thread "+ i; new Thread() { @Override public void run() {
Tue Apr 11 21:29:07 CST 2017 Thread 2 started Tue Apr 11 21:29:07 CST 2017 Thread 0 started Tue Apr 11 21:29:07 CST 2017 Thread 1 started Tue Apr 11 21:29:08 CST 2017 Thread 2 ended Tue Apr 11 21:29:08 CST 2017 Thread 1 ended Tue Apr 11 21:29:08 CST 2017 Thread 0 ended Total time : 1049ms
import java.util.Date; import java.util.concurrent.CountDownLatch;
/**
System.out.println(String.format("%s\t%s %s", new Date(), threadName, "started"));
try {
Thread.sleep(1000);
} catch (Exception ex) {
ex.printStackTrace();
}
countDown.countDown();
System.out.println(String.format("%s\t%s %s", new Date(), threadName, "ended"));
}
}.start();
}
countDown.await();
long stop = System.currentTimeMillis();
System.out.println(String.format("Total time : %sms", (stop - start)));
} } Tue Apr 11 21:29:07 CST 2017 Thread 2 started Tue Apr 11 21:29:07 CST 2017 Thread 0 started Tue Apr 11 21:29:07 CST 2017 Thread 1 started Tue Apr 11 21:29:08 CST 2017 Thread 2 ended Tue Apr 11 21:29:08 CST 2017 Thread 1 ended Tue Apr 11 21:29:08 CST 2017 Thread 0 ended Total time : 1049ms