62,614
社区成员
发帖
与我相关
我的任务
分享
package count_down_latch;
import java.util.Date;
import java.util.concurrent.CountDownLatch;
public class Test {
public static void main(String[] args) throws InterruptedException {
CountDownLatch latch = new CountDownLatch(3);
Worker worker1 = new Worker("zhangsan", 5000, latch);
Worker worker2 = new Worker("lisi", 8000, latch);
Worker worker3 = new Worker("wangwu", 10000, latch);
worker1.start();
worker2.start();
worker3.start();
latch.await(); // 等待所有工人完成工作
System.out.println("all work done at " + new Date());
}
}
class Worker extends Thread{
String workerName;
int workerTime;
CountDownLatch latch;
public Worker(String workerName, int workerTime, CountDownLatch latch) {
this.workerName = workerName;
this.workerTime = workerTime;
this.latch = latch;
}
@Override
public void run() {
System.out.println("worker " + workerName + " do work begin at " + new Date());
doWork(); // 工作了
System.out.println("woker " +workerName + " do work end at " + new Date());
latch.countDown();//工人完成工作,计数器减一
}
private void doWork(){
try {
Thread.sleep(workerTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}