CountDownLatch:概念是,允许一个或多个线程等待其他线程完成操作;
在线程基础知识中,学习过线程的join方法,当前线程阻塞等待join线程执行完毕才能执行;
测试代码如下:
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread("Thread001") {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"操作1");
}
};
Thread t2 = new Thread("Thread002") {
@Override
public void run() {
try {
System.out.println(Thread.currentThread().getName()+"操作2");
t1.join();
System.out.println("========这是第二部分内容===========");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
t1.start();
t2.start();
t2.join();
System.out.println("线程执行完毕");
}
上面代码的流程是: 1. t1和t2线程开启之后,t2.join(),主线程阻塞;
2.线程t2中,线程t1.join(),线程t2成阻塞状态;
3.等待t1结束玩成,t2才能继续执行
4.t2线程执行完毕,最后主线程执行
CountDownLatch提供了await()方法,和countDown()方法来进行线程的阻塞;await()方法阻塞当前线程,直到countDown()的个数和CountDownLatch的初始化值相同时;
public static void main(String[] args) {
try {
CountDownLatch cdt = new CountDownLatch(2);
Thread t1 = new Thread("Thread001") {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"执行了!");
cdt.countDown();
}
};
Thread t2 = new Thread("Thread002") {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "执行了!");
cdt.countDown();
}
};
t1.start();
t2.start();
cdt.await();
System.out.println("主线程执行");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
}
}