前序:
上周测试给开发的同事所开发的模块提出了一个bug,并且还是偶现。
经过仔细查看代码,发现是在业务中启用了多线程,2个线程同时跑,但是新启动的2个线程必须保证一个完成之后另一个再继续运行,才能消除bug。
什么时候用?
多线程是在很多地方都会用到的,但是我们如果想要实现在某个特定的线程运行完之后,再启动另外一个线程呢,这个时候CountDownLatch就可以派上用场了
怎么用?
先看看普通的多线程代码:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
package code; public class MyThread extends Thread { public static void main(String[] args) { MyThread th = new MyThread(); Thread t1 = new Thread(th, "Mythread" ); t1.start(); System.out.println(Thread.currentThread().getName()); } public void run() { Mythread1 th2 = new Mythread1(); Thread t2 = new Thread(th2, "Mythread1" ); t2.start(); System.out.println( this .curren
|