package com.example;
import java.util.Date;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class MyClass {
public static void main(String args[]) {
System.out.println("main->" + Thread.currentThread());
final CountDownLatch latch = new CountDownLatch(1);
System.out.println("Mission Start" + new Date().getTime());
new Thread(new Runnable() {
@Override
public void run() {
Worker worker1 = new Worker("zhang san", 2000, latch);
Worker worker2 = new Worker("Wang er", 8000, latch);
worker1.start();
worker2.start();
System.out.println("before await" + new Date().getTime());
try {
//latch.await(200, TimeUnit.MILLISECONDS);//这里只要是latch 执行完了,那么这里
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
System.out.print("InterruptedException");
}
System.out.println("after await" + new Date().getTime());
}
}).start();
System.out.println("Mission Complete" + new Date().getTime());
}
}
class Worker extends Thread{
CountDownLatch latch;
int sleepTime;
String workName;
public Worker(String workName,int sleepTime,CountDownLatch latch){
this.workName = workName;
this.sleepTime = sleepTime;
this.latch = latch;
}
@Override
public void run() {
System.out.println("worker " + workName + " start to work"+new Date().getTime());
work();
System.out.println("worker " + workName + " finish work"+new Date().getTime());
}
public void work(){
try{
Thread.sleep(sleepTime);
}catch (Exception e){
e.printStackTrace();
}finally {
latch.countDown();
}
}
}
参考;http://www.iteye.com/topic/1002652
本文介绍了一个使用Java并发工具CountDownLatch的例子。该例子通过创建两个Worker线程并利用CountDownLatch来确保主线程等待所有子线程完成后再继续执行。
306

被折叠的 条评论
为什么被折叠?



