在JDK的并发包里提供了几个非常有用的并发工具类。CountDownLatch、CyclicBarrier和Semaphore工具类提供了一种并发流程控制的手段,Exchanger工具类则提供了在线程间交换数据的一种手段。本章会配合一些应用场景来介绍如何使用这些工具类。

1,等待多线程完成的CountDownLatch

  CountDownLatch允许一个或多个线程等待其他线程完成操作
  假如有这样一个需求:我们需要解析一个Excel里多个sheet的数据,此时可以考虑使用多线程,每个线程解析一个sheet里的数据,等到所有的sheet都解析完之后,程序需要提示解析完成(或者汇总结果)。在这个需求中,要实现主线程等待所有线程完成sheet的解析操作,最简单的做法是使用join()方法,如代码清单8-1所示。

 import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger; public class JoinCountDownLatchTest {
private static Random sr=new Random(47);
private static AtomicInteger result=new AtomicInteger(0);
private static int threadCount=10;
private static class Parser implements Runnable{
String name;
public Parser(String name){
this.name=name;
}
@Override
public void run() {
int sum=0;
int seed=Math.abs(sr.nextInt()) ;
Random r=new Random(47);
for(int i=0;i<100;i++){
sum+=r.nextInt(seed);
}
result.addAndGet(sum);
System.out.println(name+"线程的解析结果:"+sum);
}
}
public static void main(String[] args) throws InterruptedException {
Thread[] threads=new Thread[threadCount];
for(int i=0;i<threadCount;i++){
threads[i]=new Thread(new Parser("Parser-"+i));
}
for(int i=0;i<threadCount;i++){
threads[i].start();
}
for(int i=0;i<threadCount;i++){
threads[i].join();
}
System.out.println("所有线程解析结束!");
System.out.println("所有线程的解析结果:"+result);
}
}

输出:

Parser-1线程的解析结果:-2013585201
Parser-0线程的解析结果:1336321192
Parser-2线程的解析结果:908136818
Parser-5线程的解析结果:-1675827227
Parser-3线程的解析结果:1638121055
Parser-4线程的解析结果:1513365118
Parser-6线程的解析结果:489607354
Parser-8线程的解析结果:1513365118
Parser-7线程的解析结果:-1191966831
Parser-9线程的解析结果:-912399159
所有线程解析结束!
所有线程的解析结果:1605138237
  join用于让当前执行线程等待join线程执行结束。其实现原理是不停检查join线程是否存活,如果join线程存活则让当前线程永远等待。其中,wait(0)表示永远等待下去,代码片段如下。join在内部使用wait进行等待。

 public class Thread implements Runnable {
......
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);//main线程永远等待join线程
}
} else {
while (isAlive()) {
long delay = millis - now;
if (delay <= 0) {
break;
}
wait(delay);
now = System.currentTimeMillis() - base;
}
}
}
......
}

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

  在JDK 1.5之后的并发包中提供的CountDownLatch也可以实现join的功能,并且比join的功能更多,如代码清单8-2所示。

 import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger; public class CountDownLatchTest {
private static Random sr=new Random(47);
private static AtomicInteger result=new AtomicInteger(0);
private static int threadCount=10;//线程数量
private static CountDownLatch countDown=new CountDownLatch(threadCount);//CountDownLatch
private static class Parser implements Runnable{
String name;
public Parser(String name){
this.name=name;
}
@Override
public void run() {
int sum=0;
int seed=Math.abs(sr.nextInt()) ;
Random r=new Random(47);
for(int i=0;i<100;i++){
sum+=r.nextInt(seed);
}
result.addAndGet(sum);
System.out.println(name+"线程的解析结果:"+sum);
countDown.countDown();//注意这里
}
}
public static void main(String[] args) throws InterruptedException {
Thread[] threads=new Thread[threadCount];
for(int i=0;i<threadCount;i++){
threads[i]=new Thread(new Parser("Parser-"+i));
}
for(int i=0;i<threadCount;i++){
threads[i].start();
}
/*
for(int i=0;i<threadCount;i++){
threads[i].join();
}*/
countDown.await();//将join改为使用CountDownLatch
System.out.println("所有线程解析结束!");
System.out.println("所有线程的解析结果:"+result);
}
}

输出:

Parser-0线程的解析结果:1336321192
Parser-1线程的解析结果:-2013585201
Parser-2线程的解析结果:-1675827227
Parser-4线程的解析结果:1638121055
Parser-3线程的解析结果:908136818
Parser-5线程的解析结果:1513365118
Parser-7线程的解析结果:489607354
Parser-6线程的解析结果:1513365118
Parser-8线程的解析结果:-1191966831
Parser-9线程的解析结果:-912399159
所有线程解析结束!
所有线程的解析结果:1605138237

  CountDownLatch的构造函数接收一个int类型的参数作为计数器,如果你想等待N个点完成,这里就传入N。
  当我们调用CountDownLatch的countDown方法时,N就会减1,CountDownLatch的await方法会阻塞当前线程,直到N变成零。由于countDown方法可以用在任何地方,所以这里说的N个点,可以是N个线程,也可以是1个线程里的N个执行步骤。用在多个线程时,只需要把这个CountDownLatch的引用传递到线程里即可。
  如果有某个解析sheet的线程处理得比较慢,我们不可能让主线程一直等待,所以可以使用另外一个带指定时间的await方法——await(long time,TimeUnit unit),这个方法等待特定时间后,就会不再阻塞当前线程。join也有类似的方法。
  注意:计数器必须大于等于0,只是等于0时候,计数器就是零,调用await方法时不会阻塞当前线程。CountDownLatch不可能重新初始化或者修改CountDownLatch对象的内部计数器的值。一个线程调用countDown方法happen-before,另外一个线程调用await方法。

 public class CountDownLatch {
/**Synchronization control For CountDownLatch. Uses AQS state to represent count.*/
private static final class Sync extends AbstractQueuedSynchronizer {
private static final long serialVersionUID = 4982264981922014374L; Sync(int count) {
setState(count);//初始化同步状态
} int getCount() {
return getState();
} protected int tryAcquireShared(int acquires) {
return (getState() == 0) ? 1 : -1;
} protected boolean tryReleaseShared(int releases) {
// Decrement count; signal when transition to zero
for (;;) {
int c = getState();
if (c == 0)
return false;
int nextc = c-1;
if (compareAndSetState(c, nextc))
return nextc == 0;
}
}
} private final Sync sync;//组合一个同步器(AQS) public CountDownLatch(int count) {
if (count < 0) throw new IllegalArgumentException("count < 0");
this.sync = new Sync(count);//初始化同步状态
}
/*Causes the current thread to wait until the latch has counted down to
     * zero, unless the thread is {@linkplain Thread#interrupt interrupted}.*/
public void await() throws InterruptedException {
sync.acquireSharedInterruptibly(1);//
} public boolean await(long timeout, TimeUnit unit)
throws InterruptedException {
return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
}
public void countDown() {
sync.releaseShared(1);//释放同步状态
} public long getCount() {
return sync.getCount();
} public String toString() {
return super.toString() + "[Count = " + sync.getCount() + "]";
}
}

2,同步屏障CyclicBarrier

  CyclicBarrier的字面意思是可循环使用(Cyclic)的屏障(Barrier)。它要做的事情是,让一组线程到达一个屏障(也可以叫同步点)时被阻塞直到最后一个线程到达屏障时,屏障才会开门,所有被屏障拦截的线程才会继续运行

  CyclicBarrier默认的构造方法是CyclicBarrier(int parties),其参数表示屏障拦截的线程数量每个线程调用await方法告诉CyclicBarrier我已经到达了屏障,然后当前线程被阻塞。但阻塞数到达设置的拦截参数,则线程一起越过屏障。

 import java.util.Random;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.atomic.AtomicInteger; public class CyclicBarrierTest { private static Random sr=new Random(47);
private static AtomicInteger result=new AtomicInteger(0);
private static int threadCount=10;
//屏障后面执行汇总
private static CyclicBarrier barrier=new CyclicBarrier(threadCount,new Accumulate());
private static class Parser implements Runnable{
String name;
public Parser(String name){
this.name=name;
}
@Override
public void run() {
int sum=0;
int seed=Math.abs(sr.nextInt()) ;
Random r=new Random(47);
for(int i=0;i<(seed%100*100000);i++){
sum+=r.nextInt(seed);
}
result.addAndGet(sum);
System.out.println(System.currentTimeMillis()+"-"+name+"线程的解析结果:"+sum);
try {
barrier.await();
System.out.println(System.currentTimeMillis()+"-"+name+"线程越过屏障!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
static class Accumulate implements Runnable{
@Override
public void run() {
System.out.println("所有线程解析结束!");
System.out.println("所有线程的解析结果:"+result);
}
}
public static void main(String[] args) throws InterruptedException {
Thread[] threads=new Thread[threadCount];
for(int i=0;i<threadCount;i++){
threads[i]=new Thread(new Parser("Parser-"+i));
}
for(int i=0;i<threadCount;i++){
threads[i].start();
}
}
}

输出:

1471866228774-Parser-4线程的解析结果:631026992
1471866228930-Parser-3线程的解析结果:-372785277
1471866228961-Parser-1线程的解析结果:-938473891
1471866229008-Parser-7线程的解析结果:-396620018
1471866229008-Parser-2线程的解析结果:-1159985406
1471866229024-Parser-5线程的解析结果:-664234808
1471866229070-Parser-6线程的解析结果:556534377
1471866229117-Parser-9线程的解析结果:-844558478
1471866229383-Parser-0线程的解析结果:919864023
1471866229430-Parser-8线程的解析结果:-2104111089
所有线程解析结束!
所有线程的解析结果:-78376279
1471866229430-Parser-8线程越过屏障!
1471866229430-Parser-2线程越过屏障!
1471866229430-Parser-9线程越过屏障!
1471866229430-Parser-7线程越过屏障!
1471866229430-Parser-1线程越过屏障!
1471866229430-Parser-3线程越过屏障!
1471866229430-Parser-0线程越过屏障!
1471866229430-Parser-6线程越过屏障!
1471866229430-Parser-4线程越过屏障!
1471866229430-Parser-5线程越过屏障!
我们发现,各个线程解析完成的时间不一致,但是越过屏障的时间却是一致的。

CyclicBarrier和CountDownLatch的区别

  CountDownLatch的计数器只能使用一次,而CyclicBarrier的计数器可以使用reset()方法重置。所以CyclicBarrier能处理更为复杂的业务场景。例如,如果计算发生错误,可以重置计数器,并让线程重新执行一次。
  CyclicBarrier还提供其他有用的方法,比如getNumberWaiting方法可以获得Cyclic-Barrier阻塞的线程数量。isBroken()方法用来了解阻塞的线程是否被中断。

3,控制并发线程数的Semaphore

  Semaphore(信号量)是用来控制同时访问特定资源的线程数量,它通过协调各个线程,以保证合理的使用公共资源。
  多年以来,我都觉得从字面上很难理解Semaphore所表达的含义,只能把它比作是控制流量的红绿灯。比如××马路要限制流量,只允许同时有一百辆车在这条路上行使,其他的都必须在路口等待,所以前一百辆车会看到绿灯,可以开进这条马路,后面的车会看到红灯,不能驶入××马路,但是如果前一百辆中有5辆车已经离开了××马路,那么后面就允许有5辆车驶入马路,这个例子里说的车就是线程,驶入马路就表示线程在执行,离开马路就表示线程执行完成,看见红灯就表示线程被阻塞,不能执行。

应用场景

  Semaphore可以用于做流量控制,特别是公用资源有限的应用场景,比如数据库连接。假如有一个需求,要读取几万个文件的数据,因为都是IO密集型任务,我们可以启动几十个线程并发地读取,但是如果读到内存后,还需要存储到数据库中,而数据库的连接数只有10个,这时我们必须控制只有10个线程同时获取数据库连接保存数据,否则会报错无法获取数据库连接。这个时候,就可以使用Semaphore来做流量控制,如代码清单8-7所示。

 import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore; public class SemaphoreTest {
private static final int THREAD_COUNT = 30;
private static ExecutorService threadPool = Executors.newFixedThreadPool(THREAD_COUNT);
private static Semaphore s = new Semaphore(10); public static void main(String[] args) {
for (int i = 0; i < THREAD_COUNT; i++) {
threadPool.execute(new Runnable() {
@Override
public void run() {
try {
s.acquire();
System.out.println("save data");
s.release();
} catch (InterruptedException e) {
}
}
});
}
threadPool.shutdown();
}
}

  在代码中,虽然有30个线程在执行,但是只允许10个并发执行。Semaphore的构造方法Semaphore(int permits)接受一个整型的数字,表示可用的许可证数量。Semaphore(10)表示允许10个线程获取许可证,也就是最大并发数是10。

  Semaphore的用法也很简单,首先线程使用Semaphore的acquire()方法获取一个许可证,使用完之后调用release()方法归还许可证。还可以用tryAcquire()方法尝试获取许可证。

其他方法

Semaphore还提供一些其他方法,具体如下。
int availablePermits():返回此信号量中当前可用的许可证数。
int getQueueLength():返回正在等待获取许可证的线程数。
boolean hasQueuedThreads():是否有线程正在等待获取许可证。
void reducePermits(int reduction):减少reduction个许可证,是个protected方法。
Collection getQueuedThreads():返回所有等待获取许可证的线程集合,是个protected方法。

4,线程间交换数据的Exchanger

  Exchanger(交换者)是一个用于线程间协作的工具类。Exchanger用于进行线程间的数据交换。它提供一个同步点,在这个同步点,两个线程可以交换彼此的数据。这两个线程通过exchange方法交换数据,如果第一个线程先执行exchange()方法,它会一直等待第二个线程也执行exchange方法,当两个线程都到达同步点时,这两个线程就可以交换数据,将本线程生产出来的数据传递给对方。
下面来看一下Exchanger的应用场景。

  1、Exchanger可以用于遗传算法,遗传算法里需要选出两个人作为交配对象,这时候会交换两人的数据,并使用交叉规则得出2个交配结果。

  2、Exchanger也可以用于校对工作,比如我们需要将纸制银行流水通过人工的方式录入成电子银行流水,为了避免错误,采用AB岗两人进行录入,录入到Excel之后,系统需要加载这两个Excel,并对两个Excel数据进行校对,看看是否录入一致.

 import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; public class ExchangerTest { private static final Exchanger<String> exgr = new Exchanger<String>();
private static ExecutorService threadPool = Executors.newFixedThreadPool(2); public static void main(String[] args) {
threadPool.execute(new Runnable() {
@Override
public void run() {
try {
String A = "银行流水100";// A录入银行流水数据
String B=exgr.exchange(A);
System.out.println("A的视角:A和B数据是否一致:" + A.equals(B) +
",A录入的是:" + A + ",B录入是:" + B);
} catch (InterruptedException e) {
}
}
});
threadPool.execute(new Runnable() {
@Override
public void run() {
try {
String B = "银行流水200";// B录入银行流水数据
String A = exgr.exchange(B);
System.out.println("B的视角:A和B数据是否一致:" + A.equals(B) +
",A录入的是:" + A + ",B录入是:" + B);
} catch (InterruptedException e) {
}
}
});
threadPool.shutdown();
}
}

输出:

B的视角:A和B数据是否一致:false,A录入的是:银行流水100,B录入是:银行流水200
A的视角:A和B数据是否一致:false,A录入的是:银行流水100,B录入是:银行流水200

如果两个线程有一个没有执行exchange()方法,则会一直等待,如果担心有特殊情况发生,避免一直等待,可以使用exchange(V x,longtimeout,TimeUnit unit)设置最大等待时长。

内容源自:

《Java并发编程的艺术》

https://blog.csdn.net/sunxianghuang/article/details/52277394

最新文章

  1. 在 JS 中使用 fetch 更加高效地进行网络请求
  2. chartControl绑定数据源
  3. Dynamic CRM 2013学习笔记 系列汇总
  4. HTML 学习笔记 CSS样式(外边框 外边框合并)
  5. 基于OWIN WebAPI 使用OAuth授权服务【客户端验证授权(Resource Owner Password Credentials Grant)】
  6. nrf51822-主从通信分析1
  7. [SAP ABAP开发技术总结]OK_CODE
  8. 分析MapReduce执行过程
  9. iOS 自定义导航栏 和状态栏
  10. 转:整理一下Entity Framework的查询
  11. 关于MYSQL优化(持续更新)
  12. 一周学会Mootools 1.4中文教程:(1)Dom选择器
  13. IT第八天 - 类的应用、debug、项目开发模式优化
  14. Unity TimeLine
  15. 谈谈装xp官方纯净系统屡次失败的深刻体会
  16. GreenDao3.2的简单使用
  17. Android异步处理系列文章四篇之一使用Thread+Handler实现非UI线程更新UI界面
  18. QT4.5.3移植到hi3536
  19. 题解——洛谷P4095 [HEOI2013]Eden 的新背包问题(背包)
  20. 002-ubuntu安装

热门文章

  1. Instagram的Material Design概念设计文章分享
  2. 使用idea2.5建立maven项目
  3. MSSQL:账号无法删除方案
  4. Android检测代理
  5. 关于offer对比
  6. BZOJ 2333 左偏树 (写得我人生都崩溃了...)
  7. 实现Brush对象的五种图形
  8. 搭建Hive所遇到的坑
  9. 【Oracle】解决oracle sqlplus 中上下左右backspace不能用
  10. 【Linux】七种文件类型