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