JAVA多线程-CountDownLatch计数器

JAVA多线程-CountDownLatch计数器

大家好,我是架构君,一个会写代码吟诗的架构师。今天说一说JAVA多线程-CountDownLatch计数器,希望能够帮助大家进步!!!

一、概述

CountDownLatch是一个同步工具类,它允许一个或多个线程等待其他线程执行完操作之后再继续执行。通常用于控制多个线程的执行顺序。

二、基本原理

我们可以把CountDownLatch看成是一个计数器,其内部维护着一个count计数,计数器的初始化值为需要控制的线程的数量,比如需要控制几个线程顺序执行我们就初始化传入几,之后每当其中一个线程完成了自己的任务后,就调用countDown()来使计数器减1;而在调用者线程中需要调用await()方法使得当前调用者线程一直处于阻塞状态,直至当计数器到达0时,就表明其他所有的线程都已经完成了任务,然后处于阻塞状态的调用者线程才可以继续往下执行。

三、应用场景

假如有这样一个需求,我们当前有一个任务,然后我们把这个任务进行分解成多个步骤完成,这个时候我们可以考虑使用多线程,每个线程完成一个步骤,等到所有的步骤都完成之后,程序提示任务完成。

对于这个需求,通常我们要实现主线程等待所有线程完成任务之后才可继续操作,最为简单的做法是直接使用join()方法,代码如下:

 

package com.feizi.java.concurrency.tool;
import java.util.concurrent.TimeUnit;
/** * Created by feizi on 2018/5/30. */
public class JoinTest { public static void main(String[] args) throws InterruptedException { Thread t1 = new Thread(new Runnable() { @Override public void run() { try { System.out.println("step one has finished..."); TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } }); Thread t2 = new Thread(new Runnable() { @Override public void run() { try { System.out.println("step two has finished..."); TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } }); t1.start(); t2.start(); t1.join(); t2.join(); System.out.println("all thread has finished..."); }
}

控制台输出结果:

 

step one has finished...
step two has finished...
all thread has finished...
Process finished with exit code 0

join()方法主要用于让当前执行线程等到join线程执行结束才可继续执行。其实现原理就是不停地去检查join线程是否处于存活状态while (isAlive()),如果join线程存活则让当前线程永远wait,我们可以看下源码,wait(0)表示永远等待下去。
join()的源码:

 

public final void join() throws InterruptedException { join(0);
}

继续跟进去:

 

public final synchronized void join(long millis) throws InterruptedException { long base = System.currentTimeMillis(); long now = 0; if (millis < 0) { throw new IllegalArgumentException("timeout value is negative"); } if (millis == 0) { while (isAlive()) { wait(0); } } else { while (isAlive()) { long delay = millis - now; if (delay <= 0) { break; } wait(delay); now = System.currentTimeMillis() - base; } } }

我们可以看到,重点是这一句,如果存活,就调用wait(0),使得永远等待。

 

while (isAlive()) { wait(0);
}

直到join线程中止后,线程的this.notifyAll()方法才会被调用,调用notifyAll是在JVM里实现的,所以JDK里看不到。

而在JDK1.5之后的并发包中提供的CountDownLatch也可以实现join的这个功能,并且比join的功能更多。

四、CountDownLatch使用

4.1、例子1-CountDownLatchTest.java类:

 

package com.feizi.java.concurrency.tool;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
/** * Created by feizi on 2018/5/30. */
public class CountDownLatchTest { private static CountDownLatch latch = new CountDownLatch(2); public static void main(String[] args) throws InterruptedException { new Thread(new Runnable() { @Override public void run() { //步骤一完成 System.out.println("step one has finished..."); try { //模拟步骤一耗时操作 TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } //步骤一完成,调用countDown()方法,计数器就减1 latch.countDown(); //步骤二完成 System.out.println("step two has finished..."); try { //模拟步骤二耗时操作 TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } //步骤二完成,调用countDown()方法,计数器就减1 latch.countDown(); } }).start(); //步骤一和步骤二完成之前会阻塞住 latch.await(); //直到所有的步骤都完成,主线程才继续执行 System.out.println("all steps have finished..."); }
}

控制台输出结果:

 

step one has finished...
step two has finished...
all steps have finished...
Process finished with exit code 0

4.2、例子2-CountDownLatchTest2.java类:

 

package com.feizi.java.concurrency.tool;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
/** * Created by feizi on 2018/5/30. */
public class CountDownLatchTest2 { private static CountDownLatch latch = new CountDownLatch(2); public static void main(String[] args) throws InterruptedException { Thread t1 = new Thread(new Runnable() { @Override public void run() { try { System.out.println("step one has finished..."); TimeUnit.SECONDS.sleep(1); //计数器减一 latch.countDown(); } catch (InterruptedException e) { e.printStackTrace(); } } }); Thread t2 = new Thread(new Runnable() { @Override public void run() { try { TimeUnit.SECONDS.sleep(1); System.out.println("step two has finished..."); //计数器减一 latch.countDown(); } catch (InterruptedException e) { e.printStackTrace(); } } }); t1.start(); t2.start(); //计数器清零之前,阻塞住当前线程 latch.await(); System.out.println("all steps have finished..."); }
}

控制台输出结果:

 

step one has finished...
step two has finished...
all steps have finished...
Process finished with exit code 0

4.3、例子3-CountDownLatchTest3.java类

 

package com.feizi.java.concurrency.tool;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
/** * Created by feizi on 2018/5/30. */
public class CountDownLatchTest3 { public static void main(String[] args) throws InterruptedException { /*线程计数器*/ CountDownLatch latch = new CountDownLatch(2); Thread t1 = new Thread(new StepOneThread(latch)); Thread t2 = new Thread(new StepTwoThread(latch)); t1.start(); t2.start(); //调用await()阻塞当前线程,直至计数器清零才可继续执行 latch.await(); TimeUnit.SECONDS.sleep(2); System.out.println("all steps has finished..."); }
}
/** * 步骤一线程 */
class StepOneThread implements Runnable{ private CountDownLatch latch; public StepOneThread(CountDownLatch latch) { this.latch = latch; } @Override public void run() { try { System.out.println("step one has finished..."); //模拟步骤一耗时操作 TimeUnit.SECONDS.sleep(2); //步骤一完成计数器减一 latch.countDown(); } catch (InterruptedException e) { e.printStackTrace(); } }
}
/** * 步骤二线程 */
class StepTwoThread implements Runnable{ private CountDownLatch latch; public StepTwoThread(CountDownLatch latch) { this.latch = latch; } @Override public void run() { try { //模拟步骤二耗时操作 TimeUnit.SECONDS.sleep(2); System.out.println("step two has finished..."); //步骤二完成计数器减一 latch.countDown(); } catch (InterruptedException e) { e.printStackTrace(); } }
}

控制台输出结果:

 

step one has finished...
step two has finished...
all steps has finished...
Process finished with exit code 0

通过上述简单的例子,我们可以看到CountDownLatch的构造函数接收一个int类型的参数作为计数器count,如果你想等待n个任务完成后再执行,那么这里就直接传入n即可。

当我们调用一次CountDownLatch的countDown()方法时,计数器count便会减1,而CountDownLatch的await()方法则会一直阻塞住当前线程,直至计数器count变为0。

最佳实践:上面所说的n个任务,可以是n个线程(上述例子2和例子3),也可以是1个线程里的n个执行步骤(上述例子1),需要注意的是在运用于多个线程时,我们只需要把这个CountDownLatch的引用传递到线程里即可。

五、其他方法

最后需要注意的是,如果有某个任务特别耗时,而我们又不可能让调用者线程(比如主线程)一直等待下去,那么就可以指定等待的时间,比如这个方法await(long time, TimeUnit unit):此方法在等待指定的时间之后不会再阻塞在当前线程,另外join也有类似的方法。

六、注意

当我们初始化一个CountDownLatch时将其计数器初始化为0,则在调用await()方法时不会阻塞当前线程。比如:

 

CountDownLatch latch = new CountDownLatch(0);

 

本文来源huayang183,由架构君转载发布,观点不代表Java架构师必看的立场,转载请标明来源出处:https://javajgs.com/archives/18059

发表评论