好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

java多线程CountDownLatch与线程池ThreadPoolExecutor/Execut

1、CountDownLatch:

一个同步工具类,它允许一个或多个线程一直等待,直到其他线程的操作执行完后再执行。

2、ThreadPoolExecutor/ExecutorService:

线程池,使用线程池可以复用线程,降低频繁创建线程造成的性能消耗,同时对线程的创建、启动、停止、销毁等操作更简便。

3、使用场景举例:

年末公司组织团建,要求每一位员工周六上午8点到公司门口集合,统一乘坐公司所租大巴前往目的地。

在这个案例中,公司作为主线程,员工作为子线程。

4、代码示例:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

package com.test.thread;

import java.util.concurrent.CountDownLatch;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.LinkedBlockingQueue;

import java.util.concurrent.ThreadPoolExecutor;

import java.util.concurrent.TimeUnit;

/**

  * @author javaloveiphone

  * @date 创建时间:2017年1月25日 上午10:59:11

  * @Description:

  */

public class Company {

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

   //员工数量

   int count = 5 ;

   //创建计数器

   //构造参数传入的数量值代表的是latch.countDown()调用的次数

   CountDownLatch latch = new CountDownLatch(count);

   //创建线程池,可以通过以下方式创建

   //ThreadPoolExecutor threadPool = new ThreadPoolExecutor(1,1,60,TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>(count));

   ExecutorService threadPool = Executors.newFixedThreadPool(count);

   System.out.println( "公司发送通知,每一位员工在周六早上8点到公司大门口集合" );

   for ( int i = 0 ;i<count ;i++){

    //将子线程添加进线程池执行

    Thread.sleep( 10 );

    threadPool.execute( new Employee(latch,i+ 1 ));

   }

   try {

    //阻塞当前线程,直到所有员工到达公司大门口之后才执行

    latch.await();

    // 使当前线程在锁存器倒计数至零之前一直等待,除非线程被中断或超出了指定的等待时间。

    //latch.await(long timeout, TimeUnit unit)

    System.out.println( "所有员工已经到达公司大门口,大巴车发动,前往活动目的地。" );

   } catch (InterruptedException e) {

    e.printStackTrace();

   } finally {

    //最后关闭线程池,但执行以前提交的任务,不接受新任务

    threadPool.shutdown();

    //关闭线程池,停止所有正在执行的活动任务,暂停处理正在等待的任务,并返回等待执行的任务列表。

    //threadPool.shutdownNow();

   }

  }

}

//分布式工作线程

class Employee implements Runnable{

  private CountDownLatch latch;

  private int employeeIndex;

  public Employee(CountDownLatch latch, int employeeIndex){

   this .latch = latch;

   this .employeeIndex = employeeIndex;

  }

  @Override

  public void run() {

   try {

    System.out.println( "员工:" +employeeIndex+ ",正在前往公司大门口集合..." );

    Thread.sleep( 10 );

    System.out.println( "员工:" +employeeIndex+ ",已到达。" );

   } catch (Exception e) {

    e.printStackTrace();

   } finally {

    //当前计算工作已结束,计数器减一

    latch.countDown();

    try {

     Thread.sleep( 10 );

    } catch (InterruptedException e) {

     e.printStackTrace();

    }

    //执行coutDown()之后,继续执行自己的工作,不受主线程的影响

    System.out.println( "员工:" +employeeIndex+ ",吃饭、喝水、拍照。" );

   }

  }

}

打印输出结果如下:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

公司发送通知,每一位员工在周六早上 8 点到公司大门口集合

员工: 1 ,正在前往公司大门口集合...

员工: 1 ,已到达。

员工: 2 ,正在前往公司大门口集合...

员工: 2 ,已到达。

员工: 1 ,吃饭、喝水、拍照。

员工: 3 ,正在前往公司大门口集合...

员工: 2 ,吃饭、喝水、拍照。

员工: 3 ,已到达。

员工: 4 ,正在前往公司大门口集合...

员工: 3 ,吃饭、喝水、拍照。

员工: 4 ,已到达。

员工: 5 ,正在前往公司大门口集合...

员工: 4 ,吃饭、喝水、拍照。

员工: 5 ,已到达。

所有员工已经到达公司大门口,大巴车发动,前往活动目的地。

员工: 5 ,吃饭、喝水、拍照。

注意:

每一个员工到达之后,执行countDown()方法,直到所有员工到达之后,计数器为0,主线程才会继续执行。

但子线程执行了countDown()方法,之后会继续自己的工作,比如上面的【吃饭、喝水、拍照】,是不受主线程是否阻塞、其它线程是否已经执行countDown()方法的影响的。

5、CountDownLatch与CyclicBarrier的对比可以看:

java多线程CyclicBarrier使用示例,让线程起步走

补充:CountDownLatch踩过的坑

线上生产环境dubbo报线程池满了,经过一天排查锁定在开三个线程计算最后合并数据的步骤中。简单描述下该步骤线程开三个 调用三个不同的方法 使用countdownlatch 计数器等待三个方法全部执行完成 合并数据。

但是由于其中一个方法调用第三方接口,接口返回异常导致转换数据报错。导致其中一个方法未正常完成。

举例demo:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

public static void main(String[] args) {

  ExecutorService executorService =Executors.newFixedThreadPool( 3 );

  CountDownLatch cdl = new CountDownLatch( 3 );

  executorService.execute( new Runnable() {

   @Override

   public void run() {

    /*try {

     function1();

    } catch (Exception e) {

     //异常处理

     e.printStackTrace();

    }

    finally {

     cdl.countDown();

    }*/

    function1();

   }

  });

  executorService.execute( new Runnable() {

   @Override

   public void run() {

    function2();

    cdl.countDown();

   }

  });

  executorService.execute( new Runnable() {

   @Override

   public void run() {

    function3();

    cdl.countDown();

   }

  });

  try {

   cdl.await();

   //cdl.await(20,TimeUnit.SECONDS);

   System.out.println( "三个执行线程结束" );

  } catch (InterruptedException e) {

   e.printStackTrace();

   System.out.println( "执行线程异常" );

  }

  finally {

   executorService.shutdown();

   System.out.println( "执行线程关闭" );

  }

}

private static void function1(){

  int i = 10 / 0 ;

  System.out.println( "方法一" );

}

private static void function2(){

  System.out.println( "方法二" );

}

private static void function3(){

  System.out.println( "方法三" );

}

方法一抛出异常,但是没有做异常处理导致不会执行线程关闭步骤,是不是和想象中不一样,一开始我也是懵,看了一下CountDownLatch原理就很好理解了,

[CountDownLatch是通过一个计数器来实现的,计数器的初始化值为线程的数量。每当一个线程完成了自己的任务后,计数器的值就相应得减1。当计数器到达0时,表示所有的线程都已完成任务,然后在闭锁上等待的线程就可以恢复执行任务。]【1】

举一个现实中例子就是:CountDownLatch 就像跑步比赛中的裁判,三个方法就是就是三位运动员,运动员2,3都已经到达终点,但是运动员1摔倒了,动不了。裁判员只看到两位运动员到达终点不能宣布比赛结束,所以一直等。。。

就像这样的场景导致线上service执行线程阻塞,接口调用次数累计导致dubbo线程满了(跟dubbo线程模型有关,有时间具体谈谈这一点)

知道原因了,就要考虑怎么修改

比赛不能无限期等,所以比赛必须在有限时间内结束,所以使用

?

1

2

3

4

public boolean await( long timeout, TimeUnit unit)

  throws InterruptedException {

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

}

线程内部也许要增加异常处理

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

executorService.execute( new Runnable() {

  @Override

  public void run() {

   try {

    function1();

   } catch (Exception e) {

    //异常处理

    e.printStackTrace();

   }

   finally {

    cdl.countDown();

   }

   // function1();

  }

});

修改后demo

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

public static void main(String[] args) {

  ExecutorService executorService =Executors.newFixedThreadPool( 3 );

  CountDownLatch cdl = new CountDownLatch( 3 );

  executorService.execute( new Runnable() {

   @Override

   public void run() {

    try {

     function1();

    } catch (Exception e) {

     //异常处理

     e.printStackTrace();

    }

    finally {

     cdl.countDown();

    }

    // function1();

   }

  });

  executorService.execute( new Runnable() {

   @Override

   public void run() {

    function2();

    cdl.countDown();

   }

  });

  executorService.execute( new Runnable() {

   @Override

   public void run() {

    function3();

    cdl.countDown();

   }

  });

  try {

   // cdl.await();

   cdl.await( 20 ,TimeUnit.SECONDS);

   System.out.println( "三个执行线程结束" );

  } catch (InterruptedException e) {

   e.printStackTrace();

   System.out.println( "执行线程异常" );

  }

  finally {

   executorService.shutdown();

   System.out.println( "执行线程关闭" );

  }

}

private static void function1(){

  int i = 10 / 0 ;

  System.out.println( "方法一" );

}

private static void function2(){

  System.out.println( "方法二" );

}

private static void function3(){

  System.out.println( "方法三" );

}

执行结果

大家结合自己的现实使用修改,爬过了使用坑,记录下分享下 ,希望能对别人有用

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。如有错误或未考虑完全的地方,望不吝赐教。

原文链接:https://blog.csdn.net/javaloveiphone/article/details/54729821

查看更多关于java多线程CountDownLatch与线程池ThreadPoolExecutor/Execut的详细内容...

  阅读:19次