zoukankan      html  css  js  c++  java
  • 并发工具

    CountDownLatch:等待多线程完成

      CountDownLatch允许一个或多个线程等待其他线程完成操作。

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

    join()方法实现代码如下:

     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;
    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         /**
    34          * join用于让当前执行线程等待join线程执行结束。其实现原理是不停检查join线程是否存活,如果join线程存活则让当前线程永远等待。
    35          *     其中,wait(0)表示永远等待下去
    36          *     通过Thread类源码可以得知,直到join线程中止后,线程的this.notifyAll()方法会被调用,调用notifyAll()方法是在JVM里实现的,所以在JDK里看不到
    37          */
    38         for(int i=0;i<threadCount;i++){
    39             threads[i].join();
    40         } 
    41         System.out.println("所有线程解析结束!");
    42         System.out.println("所有线程的解析结果:"+result);
    43     } 
    44 }

    CountDownLatch类代码实现如下:

     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 
    11     private static class Parser implements Runnable {
    12         String name;
    13 
    14         public Parser(String name) {
    15             this.name = name;
    16         }
    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 < 100; i++) {
    24                 sum += r.nextInt(seed);
    25             }
    26             result.addAndGet(sum);
    27             System.out.println(name + "线程的解析结果:" + sum);
    28             countDown.countDown();
    29         }
    30     }
    31 
    32     public static void main(String[] args) throws InterruptedException {
    33         Thread[] threads = new Thread[threadCount];
    34         for (int i = 0; i < threadCount; i++) {
    35             threads[i] = new Thread(new Parser("Parser-" + i));
    36         }
    37         for (int i = 0; i < threadCount; i++) {
    38             threads[i].start();
    39         }
    40         /*
    41          * for(int i=0;i<threadCount;i++){ threads[i].join(); }
    42          */
    43         countDown.await();// 将join改为使用CountDownLatch
    44         System.out.println("所有线程解析结束!");
    45         System.out.println("所有线程的解析结果:" + result);
    46     }
    47 }

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

     

    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 public class CyclicBarrierTest {
     6 
     7     private static Random sr = new Random(47);
     8     private static AtomicInteger result = new AtomicInteger(0);
     9     private static int threadCount = 10;
    10     // 屏障后面执行汇总
    11     private static CyclicBarrier barrier = new CyclicBarrier(threadCount, new Accumulate());
    12 
    13     private static class Parser implements Runnable {
    14         String name;
    15 
    16         public Parser(String name) {
    17             this.name = name;
    18         }
    19 
    20         @Override
    21         public void run() {
    22             int sum = 0;
    23             int seed = Math.abs(sr.nextInt());
    24             Random r = new Random(47);
    25             for (int i = 0; i < (seed % 100 * 100000); i++) {
    26                 sum += r.nextInt(seed);
    27             }
    28             result.addAndGet(sum);
    29             System.out.println(System.currentTimeMillis() + "-" + name + "线程的解析结果:" + sum);
    30             try {
    31                 barrier.await();
    32                 System.out.println(System.currentTimeMillis() + "-" + name + "线程越过屏障!");
    33             } catch (Exception e) {
    34                 e.printStackTrace();
    35             }
    36         }
    37     }
    38 
    39     static class Accumulate implements Runnable {
    40         @Override
    41         public void run() {
    42             System.out.println("所有线程解析结束!");
    43             System.out.println("所有线程的解析结果:" + result);
    44         }
    45     }
    46 
    47     public static void main(String[] args) throws InterruptedException {
    48         Thread[] threads = new Thread[threadCount];
    49         for (int i = 0; i < threadCount; i++) {
    50             threads[i] = new Thread(new Parser("Parser-" + i));
    51         }
    52         for (int i = 0; i < threadCount; i++) {
    53             threads[i].start();
    54         }
    55     }
    56 }

    各个线程解析完成的时间不一致,但是越过屏障的时间却是一致的。

    CyclicBarrier和CountDownLatch的区别:

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

    Semaphore:控制并发线程数

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

    应用场景:

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

     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) + ",A录入的是:" + A + ",B录入是:" + B);
    18                 } catch (InterruptedException e) {
    19                 }
    20             }
    21         });
    22         threadPool.execute(new Runnable() {
    23             @Override
    24             public void run() {
    25                 try {
    26                     String B = "银行流水200";// B录入银行流水数据
    27                     String A = exgr.exchange(B);
    28                     System.out.println("B的视角:A和B数据是否一致:" + A.equals(B) + ",A录入的是:" + A + ",B录入是:" + B);
    29                 } catch (InterruptedException e) {
    30                 }
    31             }
    32         });
    33         threadPool.shutdown();
    34     }
    35 }

    输出:

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

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

  • 相关阅读:
    作业3月30号
    21、,模块与包的使用
    作业3月26号
    20、面向函数与匿名函数及模块
    作业3月25号
    19、迭代器及函数的递归调用
    作业3月24号
    06-函数
    3.17---购物车练习
    3.15---文件处理练习2
  • 原文地址:https://www.cnblogs.com/wang1001/p/9603511.html
Copyright © 2011-2022 走看看