个人理解就是当指定数量的线程全部执行完毕后再进行下一步动作
package study;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class Test {
public static class myThread extends Thread {
int sleepSeconds;
CountDownLatch countDownLatch;
public myThread(String name,int seconds,CountDownLatch countDownLatch) {
this.setName(name);
this.sleepSeconds = seconds;
this.countDownLatch = countDownLatch;
}
@Override
public void run() {
long startTime = System.currentTimeMillis();
System.out.println(this.getName() + "开始执行");
try {
TimeUnit.SECONDS.sleep(sleepSeconds);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
countDownLatch.countDown();
}
long endTime = System.currentTimeMillis();
System.out.println(this.getName() + "结束执行,耗时:" + String.valueOf(endTime - startTime));
}
}
public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(3);
long start = System.currentTimeMillis();
System.out.println("------主线程开始------");
myThread t3 = new myThread("线程3", 3,countDownLatch);
t3.start();
myThread t1 = new myThread("线程1", 2,countDownLatch);
t1.start();
myThread t2 = new myThread("线程2", 5,countDownLatch);
t2.start();
countDownLatch.await();
long end = System.currentTimeMillis();
System.out.println("主线程执行完毕,耗时:" + String.valueOf(end - start));
}
}
这个实现了类似上一篇文章的join效果