Java并发工具类详解

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

等待多线程完成的CountDownLatch

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

 
  1. import java.util.Random;

  2. import java.util.concurrent.atomic.AtomicInteger;

  3.  
  4. public class JoinCountDownLatchTest {

  5. private static Random sr=new Random(47);

  6. private static AtomicInteger result=new AtomicInteger(0);

  7. private static int threadCount=10;

  8. private static class Parser implements Runnable{

  9. String name;

    扫描二维码关注公众号,回复: 3634445 查看本文章
  10. public Parser(String name){

  11. this.name=name;

  12. }

  13. @Override

  14. public void run() {

  15. int sum=0;

  16. int seed=Math.abs(sr.nextInt()) ;

  17. Random r=new Random(47);

  18. for(int i=0;i<100;i++){

  19. sum+=r.nextInt(seed);

  20. }

  21. result.addAndGet(sum);

  22. System.out.println(name+"线程的解析结果:"+sum);

  23. }

  24. }

  25. public static void main(String[] args) throws InterruptedException {

  26. Thread[] threads=new Thread[threadCount];

  27. for(int i=0;i<threadCount;i++){

  28. threads[i]=new Thread(new Parser("Parser-"+i));

  29. }

  30. for(int i=0;i<threadCount;i++){

  31. threads[i].start();

  32. }

  33. for(int i=0;i<threadCount;i++){

  34. threads[i].join();

  35. }

  36. System.out.println("所有线程解析结束!");

  37. System.out.println("所有线程的解析结果:"+result);

  38. }

  39. }

输出:

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)表示永远等待下去,代码片段如下。

 
  1. public class Thread implements Runnable {

  2. ......

  3. public final void join() throws InterruptedException {

  4. join(0);

  5. }

  6. public final synchronized void join(long millis)

  7. throws InterruptedException {

  8. long base = System.currentTimeMillis();

  9. long now = 0;

  10.  
  11. if (millis < 0) {

  12. throw new IllegalArgumentException("timeout value is negative");

  13. }

  14.  
  15. if (millis == 0) {//执行到这里

  16. while (isAlive()) {

  17. wait(0);//main线程永远等待join线程

  18. }

  19. } else {

  20. while (isAlive()) {

  21. long delay = millis - now;

  22. if (delay <= 0) {

  23. break;

  24. }

  25. wait(delay);

  26. now = System.currentTimeMillis() - base;

  27. }

  28. }

  29. }

  30. ......

  31. }

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

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

 
  1. import java.util.Random;

  2. import java.util.concurrent.CountDownLatch;

  3. import java.util.concurrent.atomic.AtomicInteger;

  4.  
  5. public class CountDownLatchTest {

  6. private static Random sr=new Random(47);

  7. private static AtomicInteger result=new AtomicInteger(0);

  8. private static int threadCount=10;//线程数量

  9. private static CountDownLatch countDown=new CountDownLatch(threadCount);//CountDownLatch

  10. private static class Parser implements Runnable{

  11. String name;

  12. public Parser(String name){

  13. this.name=name;

  14. }

  15. @Override

  16. public void run() {

  17. int sum=0;

  18. int seed=Math.abs(sr.nextInt()) ;

  19. Random r=new Random(47);

  20. for(int i=0;i<100;i++){

  21. sum+=r.nextInt(seed);

  22. }

  23. result.addAndGet(sum);

  24. System.out.println(name+"线程的解析结果:"+sum);

  25. countDown.countDown();//注意这里

  26. }

  27. }

  28. public static void main(String[] args) throws InterruptedException {

  29. Thread[] threads=new Thread[threadCount];

  30. for(int i=0;i<threadCount;i++){

  31. threads[i]=new Thread(new Parser("Parser-"+i));

  32. }

  33. for(int i=0;i<threadCount;i++){

  34. threads[i].start();

  35. }

  36. /*

  37. for(int i=0;i<threadCount;i++){

  38. threads[i].join();

  39. }*/

  40. countDown.await();//将join改为使用CountDownLatch

  41. System.out.println("所有线程解析结束!");

  42. System.out.println("所有线程的解析结果:"+result);

  43. }

  44. }

输出:

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方法。

 
  1. public class CountDownLatch {

  2. /**Synchronization control For CountDownLatch. Uses AQS state to represent count.*/

  3. private static final class Sync extends AbstractQueuedSynchronizer {

  4. private static final long serialVersionUID = 4982264981922014374L;

  5.  
  6. Sync(int count) {

  7. setState(count);//初始化同步状态

  8. }

  9.  
  10. int getCount() {

  11. return getState();

  12. }

  13.  
  14. protected int tryAcquireShared(int acquires) {

  15. return (getState() == 0) ? 1 : -1;

  16. }

  17.  
  18. protected boolean tryReleaseShared(int releases) {

  19. // Decrement count; signal when transition to zero

  20. for (;;) {

  21. int c = getState();

  22. if (c == 0)

  23. return false;

  24. int nextc = c-1;

  25. if (compareAndSetState(c, nextc))

  26. return nextc == 0;

  27. }

  28. }

  29. }

  30.  
  31. private final Sync sync;//组合一个同步器(AQS)

  32.  
  33. public CountDownLatch(int count) {

  34. if (count < 0) throw new IllegalArgumentException("count < 0");

  35. this.sync = new Sync(count);//初始化同步状态

  36. }

  37. /*Causes the current thread to wait until the latch has counted down to

  38.      * zero, unless the thread is {@linkplain Thread#interrupt interrupted}.*/

  39. public void await() throws InterruptedException {

  40. sync.acquireSharedInterruptibly(1);//

  41. }

  42.  
  43. public boolean await(long timeout, TimeUnit unit)

  44. throws InterruptedException {

  45. return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));

  46. }

  47. public void countDown() {

  48. sync.releaseShared(1);//释放同步状态

  49. }

  50.  
  51. public long getCount() {

  52. return sync.getCount();

  53. }

  54.  
  55. public String toString() {

  56. return super.toString() + "[Count = " + sync.getCount() + "]";

  57. }

  58. }

同步屏障CyclicBarrier

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

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

 
  1. import java.util.Random;

  2. import java.util.concurrent.CyclicBarrier;

  3. import java.util.concurrent.atomic.AtomicInteger;

  4.  
  5.  
  6. public class CyclicBarrierTest {

  7.  
  8. private static Random sr=new Random(47);

  9. private static AtomicInteger result=new AtomicInteger(0);

  10. private static int threadCount=10;

  11. //屏障后面执行汇总

  12. private static CyclicBarrier barrier=new CyclicBarrier(threadCount,new Accumulate());

  13. private static class Parser implements Runnable{

  14. String name;

  15. public Parser(String name){

  16. this.name=name;

  17. }

  18. @Override

  19. public void run() {

  20. int sum=0;

  21. int seed=Math.abs(sr.nextInt()) ;

  22. Random r=new Random(47);

  23. for(int i=0;i<(seed%100*100000);i++){

  24. sum+=r.nextInt(seed);

  25. }

  26. result.addAndGet(sum);

  27. System.out.println(System.currentTimeMillis()+"-"+name+"线程的解析结果:"+sum);

  28. try {

  29. barrier.await();

  30. System.out.println(System.currentTimeMillis()+"-"+name+"线程越过屏障!");

  31. } catch (Exception e) {

  32. e.printStackTrace();

  33. }

  34. }

  35. }

  36. static class Accumulate implements Runnable{

  37. @Override

  38. public void run() {

  39. System.out.println("所有线程解析结束!");

  40. System.out.println("所有线程的解析结果:"+result);

  41. }

  42. }

  43. public static void main(String[] args) throws InterruptedException {

  44. Thread[] threads=new Thread[threadCount];

  45. for(int i=0;i<threadCount;i++){

  46. threads[i]=new Thread(new Parser("Parser-"+i));

  47. }

  48. for(int i=0;i<threadCount;i++){

  49. threads[i].start();

  50. }

  51. }

  52. }

输出:

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()方法用来了解阻塞的线程是否被中断。

控制并发线程数的Semaphore

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

应用场景

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

 
  1. import java.util.concurrent.ExecutorService;

  2. import java.util.concurrent.Executors;

  3. import java.util.concurrent.Semaphore;

  4.  
  5. public class SemaphoreTest {

  6. private static final int THREAD_COUNT = 30;

  7. private static ExecutorService threadPool = Executors.newFixedThreadPool(THREAD_COUNT);

  8. private static Semaphore s = new Semaphore(10);

  9.  
  10. public static void main(String[] args) {

  11. for (int i = 0; i < THREAD_COUNT; i++) {

  12. threadPool.execute(new Runnable() {

  13. @Override

  14. public void run() {

  15. try {

  16. s.acquire();

  17. System.out.println("save data");

  18. s.release();

  19. } catch (InterruptedException e) {

  20. }

  21. }

  22. });

  23. }

  24. threadPool.shutdown();

  25. }

  26. }

在代码中,虽然有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方法。

线程间交换数据的Exchanger

Exchanger(交换者)是一个用于线程间协作的工具类。Exchanger用于进行线程间的数据交换。它提供一个同步点,在这个同步点,两个线程可以交换彼此的数据。这两个线程通过exchange方法交换数据,如果第一个线程先执行exchange()方法,它会一直等待第二个线程也执行exchange方法,当两个线程都到达同步点时,这两个线程就可以交换数据,将本线程生产出来的数据传递给对方。
下面来看一下Exchanger的应用场景。
1、Exchanger可以用于遗传算法,遗传算法里需要选出两个人作为交配对象,这时候会交换两人的数据,并使用交叉规则得出2个交配结果。

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

 
  1. import java.util.concurrent.Exchanger;

  2. import java.util.concurrent.ExecutorService;

  3. import java.util.concurrent.Executors;

  4.  
  5. public class ExchangerTest {

  6.  
  7. private static final Exchanger<String> exgr = new Exchanger<String>();

  8. private static ExecutorService threadPool = Executors.newFixedThreadPool(2);

  9.  
  10. public static void main(String[] args) {

  11. threadPool.execute(new Runnable() {

  12. @Override

  13. public void run() {

  14. try {

  15. String A = "银行流水100";// A录入银行流水数据

  16. String B=exgr.exchange(A);

  17. System.out.println("A的视角:A和B数据是否一致:" + A.equals(B) +

  18. ",A录入的是:" + A + ",B录入是:" + B);

  19. } catch (InterruptedException e) {

  20. }

  21. }

  22. });

  23. threadPool.execute(new Runnable() {

  24. @Override

  25. public void run() {

  26. try {

  27. String B = "银行流水200";// B录入银行流水数据

  28. String A = exgr.exchange(B);

  29. System.out.println("B的视角:A和B数据是否一致:" + A.equals(B) +

  30. ",A录入的是:" + A + ",B录入是:" + B);

  31. } catch (InterruptedException e) {

  32. }

  33. }

  34. });

  35. threadPool.shutdown();

  36. }

  37. }

输出:

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

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

猜你喜欢

转载自blog.csdn.net/belalds/article/details/82662606