CountDownLatch怎么在JAVA中使用

  介绍

本篇文章为大家展示了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秒,这样运行代码,就会打印出:

 CountDownLatch怎么在JAVA中使用“> </p> <p>从上面的输出顺序可以看出,先是启动了主要线程,然后再启动了MyThread线程,在MyThread线程中,又启动了MyThread1线程。但是由于让MyThread1线程睡了1秒,模拟处理后续业务,这样他就比MyThread运行完毕的时间晚一些。</p> <p>现在,在代码中加上CountDownLatch,要让MyThread1先运行完毕,再让MyThread继续运行。</p> <pre类= 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中使用