使用 CountDownLatch 控制多个线程执行顺序
有时候会有这样的需求,多个线程同时工作,然后其中几个可以随意并发执行,但有一个线程需要等其他线程工作结束后,才能开始。举个例子,开启多个线程分块下载一个大文件,每个线程只下载固定的一截,最后由另外一个线程来拼接所有的分段,那么这时候我们可以考虑使用CountDownLatch来控制并发。
CountDownLatch是JAVA提供在java.util.concurrent包下的一个辅助类,可以把它看成是一个计数器,其内部维护着一个count计数,只不过对这个计数器的操作都是原子操作,同时只能有一个线程去操作这个计数器,CountDownLatch通过构造函数传入一个初始计数值,调用者可以通过调用CounDownLatch对象的cutDown()方法,来使计数减1;如果调用对象上的await()方法,那么调用者就会一直阻塞在这里,直到别人通过cutDown方法,将计数减到0,才可以继续执行。
CountDownLatch类有3个基本元素:
1.初始值决定CountDownLatch类需要等待的事件的数量。
2.await() 方法, 被等待全部事件终结的线程调用。
3.countDown() 方法,事件在结束执行后调用。
当创建 CountDownLatch 对象时,对象使用构造函数的参数来初始化内部计数器。
每次调用 countDown() 方法, CountDownLatch 对象内部计数器减一。
当内部计数器达到0时, CountDownLatch 对象唤醒全部使用 await() 方法睡眠的线程们。
不可能重新初始化或者修改CountDownLatch对象的内部计数器的值。
一旦计数器的值初始后,唯一可以修改它的方法就是之前用的 countDown() 方法。
当计数器到达0时, 全部调用 await() 方法会立刻返回,接下来任何countDown() 方法的调用都将不会造成任何影响。
示例
1 import java.util.concurrent.CountDownLatch;
2
3 public class Sample {
4 /**
5 * 计数器,用来控制线程
6 * 传入参数2,表示计数器计数为2
7 */
8 private final static CountDownLatch mCountDownLatch = new CountDownLatch(2);
9
10 /**
11 * 示例工作线程类
12 */
13 private static class WorkingThread extends Thread {
14 private final String mThreadName;
15 private final int mSleepTime;
16 public WorkingThread(String name, int sleepTime) {
17 mThreadName = name;
18 mSleepTime = sleepTime;
19 }
20
21 @Override
22 public void run() {
23 System.out.println("[" + mThreadName + "] started!");
24 try {
25 Thread.sleep(mSleepTime);
26 } catch (InterruptedException e) {
27 e.printStackTrace();
28 }
29 mCountDownLatch.countDown();
30 System.out.println("[" + mThreadName + "] end!");
31 }
32 }
33
34 /**
35 * 示例线程类
36 */
37 private static class SampleThread extends Thread {
38
39 @Override
40 public void run() {
41 System.out.println("[SampleThread] started!");
42 try {
43 // 会阻塞在这里等待 mCountDownLatch 里的count变为0;
44 // 也就是等待另外的WorkingThread调用countDown()
45 mCountDownLatch.await();
46 } catch (InterruptedException e) {
47
48 }
49 System.out.println("[SampleThread] end!");
50 }
51 }
52
53 public static void main(String[] args) throws Exception {
54 // 最先run SampleThread
55 new SampleThread().start();
56 // 运行两个工作线程
57 // 工作线程1运行5秒
58 new WorkingThread("WorkingThread1", 5000).start();
59 // 工作线程2运行2秒
60 new WorkingThread("WorkingThread2", 2000).start();
61 }
62 }
运行结果:
[SampleThread] started!
[WorkingThread1] started!
[WorkingThread2] started!
[WorkingThread2] end!
[WorkingThread1] end!
[SampleThread] end!
达到了目的。当然还有其他方式可以做到这样的效果,本文仅仅是介绍了一种使用CountDownLatch的方式。
指定并发数测试
public class AddCalcParallelRequestThread implements Runnable { private CountDownLatch signal; private CountDownLatch finish; private int taskNumber = 0; private AddCalculate calc; public AddCalcParallelRequestThread(AddCalculate calc, CountDownLatch signal, CountDownLatch finish, int taskNumber) { this.signal = signal; this.finish = finish; this.taskNumber = taskNumber; this.calc = calc; } public void run() { try { signal.await();//当前线程等待 int add = calc.add(taskNumber, taskNumber); System.out.println(System.currentTimeMillis()+" s="+signal.getCount()+" f="+ finish.getCount()+" "+Thread.currentThread()+" calc add result:[" + add + "]"); finish.countDown(); } catch (InterruptedException ex) { Logger.getLogger(AddCalcParallelRequestThread.class.getName()).log(Level.SEVERE, null, ex); } } }
测试
public static void parallelAddCalcTask(AddCalculate calc) throws InterruptedException { //并行度10 int parallel = 10; //开始计时 StopWatch sw = new StopWatch(); sw.start(); CountDownLatch signal = new CountDownLatch(1); CountDownLatch finish = new CountDownLatch(parallel); for (int index = 0; index < parallel; index++) { AddCalcParallelRequestThread client = new AddCalcParallelRequestThread(calc, signal, finish, index); new Thread(client).start(); } System.out.println("wait time 10s"); Thread.sleep(10000); System.out.println("start"); signal.countDown();//开始执行 finish.await();//等待所有线程结束 sw.stop(); String tip = String.format("加法计算RPC调用总共耗时: [%s] 毫秒", sw.getTime()); System.out.println(tip); }
wait time 10s start 1499914454867 s=0 f=10 Thread[Thread-11,5,main] calc add result:[18] 1499914454867 s=0 f=10 Thread[Thread-4,5,main] calc add result:[4] 1499914454867 s=0 f=10 Thread[Thread-8,5,main] calc add result:[12] 1499914454868 s=0 f=7 Thread[Thread-10,5,main] calc add result:[16] 1499914454869 s=0 f=6 Thread[Thread-2,5,main] calc add result:[0] 1499914454869 s=0 f=5 Thread[Thread-6,5,main] calc add result:[8] 1499914454870 s=0 f=4 Thread[Thread-3,5,main] calc add result:[2] 1499914454870 s=0 f=3 Thread[Thread-7,5,main] calc add result:[10] 1499914454870 s=0 f=2 Thread[Thread-9,5,main] calc add result:[14] 1499914454870 s=0 f=1 Thread[Thread-5,5,main] calc add result:[6] 加法计算RPC调用总共耗时: [10503] 毫秒
十个线程同时执行操作
本文介绍如何使用Java的CountDownLatch来控制多个线程的执行顺序,实现主线程等待子线程完成后再继续执行的场景。CountDownLatch作为并发工具类,能够帮助开发者精确控制线程的启动和等待。

571

被折叠的 条评论
为什么被折叠?



