本篇文章为大家展示了CountDownLatch怎么在JAVA中使用,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。
<强>什么时候用? 强>
多线程是在很多地方都会用到的,但是我们如果想要实现在某个特定的线程运行完之后,再启动另外一个线程呢,这个时候CountDownLatch就可以派上用场了
<强>怎么用? 强>
先看看普通的多线程代码:
package 代码; public class  MyThread extends Thread  {, public 才能;static  void main (String [], args), {,, ,,,MyThread th =, new MyThread ();,, ,,,Thread t1 =, new 线程(th,“Mythread"),,,,, ,,,t1.start (),, ,,,System.out.println (Thread.currentThread () . getname ()),, ,,,},,,, ,,,public void 运行(), ,,,,,{,, ,,,,,,,Mythread1 th3 =, new Mythread1 ();,, ,,,,,,,Thread t2 =, new 线程(th3,“Mythread1"),,,,, ,,,,,,,t2.start (),, ,,,,,,,System.out.println (this.currentThread () . getname ()),, ,,,,,}, ,,,class Mythread1 extends 线程 ,,,{ ,,,,,public void 运行(),{,, ,,,,,,,try { ,,,,,,,,,thread . sleep (1000); ,,,,,,,},catch (InterruptedException e), { ,,,,,,,,,//,TODO Auto-generated catch 块 ,,,,,,,,,e.printStackTrace (); ,,,,,,,} ,,,,,,,System.out.println (this.currentThread () . getname ()),, ,,,,,,,}, ,,,,, ,,,} 以前,,}>代码如上,先用MyThread继承了线程类,然后在MyThread类内部又写了一个MyThread1类,同样也是继承了线程类,并且在运行方法里面让它睡1秒,这样运行代码,就会打印出:
package 代码; import java.util.concurrent.CountDownLatch; public class  MyThread extends Thread  {, CountDownLatch 才能;CountDownLatch =, new CountDownLatch (1); public 才能;static  void main (String [], args), {,, ,,,MyThread th =, new MyThread ();,, ,,,Thread t1 =, new 线程(th,“Mythread"),,,,, ,,,t1.start (),, ,,,System.out.println (Thread.currentThread () . getname ()),, ,,,},,,, ,,,public void 运行(), ,,,,,{,, ,,,,,,,Mythread1 th3 =, new Mythread1 ();,, ,,,,,,,Thread t2 =, new 线程(th3,“Mythread1"),,,,, ,,,,,,,t2.start (),, ,,,,,,,try { ,,,,,,,,,countDownLatch.await (); ,,,,,,,},catch (InterruptedException e), { ,,,,,,,,,e.printStackTrace (); ,,,,,,,} ,,,,,,,System.out.println (this.currentThread () . getname ()),, ,,,,,}, ,,,class Mythread1 extends 线程 ,,,{ ,,,,,public void 运行(),{,, ,,,,,,,try { ,,,,,,,,,thread . sleep (1000); ,,,,,,,},catch (InterruptedException e), { ,,,,,,,,,e.printStackTrace (); ,,,,,,,} null null null null null null
CountDownLatch怎么在JAVA中使用