Java线程的并发工具类

曾经终败给现在 2024-03-27 18:57 201阅读 0赞

Java线程的并发工具类。

一、fork/join

1. Fork-Join原理

在必要的情况下,将一个大任务,拆分(fork)成若干个小任务,然后再将一个个小任务的结果进行汇总(join)。

适用场景:大数据量统计类任务。

图片

2. 工作窃取

Fork/Join在实现上,大任务拆分出来的小任务会被分发到不同的队列里面,每一个队列都会用一个线程来消费,这是为了获取任务时的多线程竞争,但是某些线程会提前消费完自己的队列。而有些线程没有及时消费完队列,这个时候,完成了任务的线程就会去窃取那些没有消费完成的线程的任务队列,为了减少线程竞争,Fork/Join使用双端队列来存取小任务,分配给这个队列的线程会一直从头取得一个任务然后执行,而窃取线程总是从队列的尾端拉取task。

3. 代码实现

我们要使用 ForkJoin 框架,必须首先创建一个 ForkJoin 任务。它提供在任务中执行 fork 和 join 的操作机制,通常我们不直接继承 ForkjoinTask 类,只需要直接继承其子类。

1、RecursiveAction,用于没有返回结果的任务。
2、RecursiveTask,用于有返回值的任务。

task 要通过 ForkJoinPool 来执行,使用 invoke、execute、submit提交,两者的区别是:invoke 是同步执行,调用之后需要等待任务完成,才能执行后面的代码;execute、submit 是异步执行。

示例1:长度400万的随机数组求和,使用RecursiveTask 。

  1. /**
  2. * 随机产生ARRAY_LENGTH长的的随机数组
  3. */
  4. public class MakeArray {
  5. // 数组长度
  6. public static final int ARRAY_LENGTH = 4000000;
  7. public static int[] makeArray() {
  8. // new一个随机数发生器
  9. Random r = new Random();
  10. int[] result = new int[ARRAY_LENGTH];
  11. for (int i = 0; i < ARRAY_LENGTH; i++) {
  12. // 用随机数填充数组
  13. result[i] = r.nextInt(ARRAY_LENGTH * 3);
  14. }
  15. return result;
  16. }
  17. }
  18. public class SumArray {
  19. private static class SumTask extends RecursiveTask<Integer> {
  20. // 阈值
  21. private final static int THRESHOLD = MakeArray.ARRAY_LENGTH / 10;
  22. private int[] src;
  23. private int fromIndex;
  24. private int toIndex;
  25. public SumTask(int[] src, int fromIndex, int toIndex) {
  26. this.src = src;
  27. this.fromIndex = fromIndex;
  28. this.toIndex = toIndex;
  29. }
  30. @Override
  31. protected Integer compute() {
  32. // 任务的大小是否合适
  33. if ((toIndex - fromIndex) < THRESHOLD) {
  34. System.out.println(" from index = " + fromIndex + " toIndex=" + toIndex);
  35. int count = 0;
  36. for (int i = fromIndex; i <= toIndex; i++) {
  37. count = count + src[i];
  38. }
  39. return count;
  40. } else {
  41. // fromIndex....mid.....toIndex
  42. int mid = (fromIndex + toIndex) / 2;
  43. SumTask left = new SumTask(src, fromIndex, mid);
  44. SumTask right = new SumTask(src, mid + 1, toIndex);
  45. invokeAll(left, right);
  46. return left.join() + right.join();
  47. }
  48. }
  49. }
  50. public static void main(String[] args) {
  51. int[] src = MakeArray.makeArray();
  52. // new出池的实例
  53. ForkJoinPool pool = new ForkJoinPool();
  54. // new出Task的实例
  55. SumTask innerFind = new SumTask(src, 0, src.length - 1);
  56. long start = System.currentTimeMillis();
  57. // invoke阻塞方法
  58. pool.invoke(innerFind);
  59. System.out.println("Task is Running.....");
  60. System.out.println("The count is " + innerFind.join()
  61. + " spend time:" + (System.currentTimeMillis() - start) + "ms");
  62. }
  63. }

示例2:遍历指定目录(含子目录)下面的txt文件。

  1. public class FindDirsFiles extends RecursiveAction {
  2. private File path;
  3. public FindDirsFiles(File path) {
  4. this.path = path;
  5. }
  6. @Override
  7. protected void compute() {
  8. List<FindDirsFiles> subTasks = new ArrayList<>();
  9. File[] files = path.listFiles();
  10. if (files!=null){
  11. for (File file : files) {
  12. if (file.isDirectory()) {
  13. // 对每个子目录都新建一个子任务。
  14. subTasks.add(new FindDirsFiles(file));
  15. } else {
  16. // 遇到文件,检查。
  17. if (file.getAbsolutePath().endsWith("txt")){
  18. System.out.println("文件:" + file.getAbsolutePath());
  19. }
  20. }
  21. }
  22. if (!subTasks.isEmpty()) {
  23. // 在当前的 ForkJoinPool 上调度所有的子任务。
  24. for (FindDirsFiles subTask : invokeAll(subTasks)) {
  25. subTask.join();
  26. }
  27. }
  28. }
  29. }
  30. public static void main(String [] args){
  31. try {
  32. // 用一个 ForkJoinPool 实例调度总任务
  33. ForkJoinPool pool = new ForkJoinPool();
  34. FindDirsFiles task = new FindDirsFiles(new File("F:/"));
  35. // 异步提交
  36. pool.execute(task);
  37. // 主线程做自己的业务工作
  38. System.out.println("Task is Running......");
  39. Thread.sleep(1);
  40. int otherWork = 0;
  41. for(int i=0;i<100;i++){
  42. otherWork = otherWork+i;
  43. }
  44. System.out.println("Main Thread done sth......,otherWork=" + otherWork);
  45. System.out.println("Task end");
  46. } catch (Exception e) {
  47. e.printStackTrace();
  48. }
  49. }
  50. }

二、CountDownLatch

闭锁,CountDownLatch 这个类能够使一个线程等待其他线程完成各自的工作后再执行。例如,应用程序的主线程希望在负责启动框架服务的线程已经启动所有的框架服务之后再执行。

CountDownLatch 是通过一个计数器来实现的,计数器的初始值为初始任务的数量。每当完成了一个任务后,计数器的值就会减 1(CountDownLatch.countDown()方法)。当计数器值到达 0 时,它表示所有的已经完成了任务,然后在闭锁上等待 CountDownLatch.await()方法的线程就可以恢复执行任务。

示例代码:

  1. public class CountDownLatchTest {
  2. private static CountDownLatch countDownLatch = new CountDownLatch(2);
  3. private static class BusinessThread extends Thread {
  4. @Override
  5. public void run() {
  6. try {
  7. System.out.println("BusinessThread " + Thread.currentThread().getName() + " start....");
  8. Thread.sleep(3000);
  9. System.out.println("BusinessThread " + Thread.currentThread().getName() + " end.....");
  10. // 计数器减1
  11. countDownLatch.countDown();
  12. } catch (InterruptedException e) {
  13. e.printStackTrace();
  14. }
  15. }
  16. }
  17. public static void main(String[] args) throws InterruptedException {
  18. System.out.println("main start....");
  19. new BusinessThread().start();
  20. new BusinessThread().start();
  21. // 等待countDownLatch计数器为零后执行后面代码
  22. countDownLatch.await();
  23. System.out.println("main end");
  24. }
  25. }

注意点:

1、CountDownLatch(2)并不代表对应两个线程。

2、一个线程中可以多次countDownLatch.countDown(),比如在一个线程中countDown两次或者多次。

三、CyclicBarrier

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

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

CyclicBarrier 还提供一个更高级的构造函数 CyclicBarrie(r int parties,Runnable barrierAction),用于在线程全部到达屏障时,优先执行 barrierAction,方便处理更复杂的业务场景。

示例代码:

  1. public class CyclicBarrierTest {
  2. private static CyclicBarrier barrier = new CyclicBarrier(4, new CollectThread());
  3. /**
  4. * 存放子线程工作结果的容器
  5. */
  6. private static ConcurrentHashMap<String, Long> resultMap = new ConcurrentHashMap<>();
  7. public static void main(String[] args) {
  8. for (int i = 0; i < 4; i++) {
  9. Thread thread = new Thread(new SubThread());
  10. thread.start();
  11. }
  12. }
  13. /**
  14. * 汇总的任务
  15. */
  16. private static class CollectThread implements Runnable {
  17. @Override
  18. public void run() {
  19. StringBuilder result = new StringBuilder();
  20. for (Map.Entry<String, Long> workResult : resultMap.entrySet()) {
  21. result.append("[" + workResult.getValue() + "]");
  22. }
  23. System.out.println(" the result = " + result);
  24. System.out.println("colletThread end.....");
  25. }
  26. }
  27. /**
  28. * 相互等待的子线程
  29. */
  30. private static class SubThread implements Runnable {
  31. @Override
  32. public void run() {
  33. long id = Thread.currentThread().getId();
  34. resultMap.put(Thread.currentThread().getId() + "", id);
  35. try {
  36. Thread.sleep(1000 + id);
  37. System.out.println("Thread_" + id + " end1.....");
  38. barrier.await();
  39. Thread.sleep(1000 + id);
  40. System.out.println("Thread_" + id + " end2.....");
  41. barrier.await();
  42. } catch (Exception e) {
  43. e.printStackTrace();
  44. }
  45. }
  46. }
  47. }

注意: 一个线程中可以多次await();

四、Semaphore

Semaphore(信号量)是用来控制同时访问特定资源的线程数量,它通过协调各个线程,以保证合理的使用公共资源。应用场景 Semaphore 可以用于做流量控制,特别是公用资源有限的应用场景,比如数据库连接池数量。

方法:常用的前4个。


































方法 描述
acquire() 获取连接
release() 归还连接数
intavailablePermits() 返回此信号量中当前可用的许可证数
intgetQueueLength() 返回正在等待获取许可证的线程数
void reducePermit(s int reduction) 减少 reduction 个许可证,是个 protected 方法
Collection getQueuedThreads() 返回所有等待获取许可证的线程集合,是个 protected 方法

示例代码:模拟数据库连接池。

  1. /**
  2. * 数据库连接
  3. */
  4. public class SqlConnectImpl implements Connection {
  5. /**
  6. * 得到一个数据库连接
  7. */
  8. public static final Connection fetchConnection(){
  9. return new SqlConnectImpl();
  10. }
  11. // 省略其他代码
  12. }
  13. /**
  14. * 连接池代码
  15. */
  16. public class DBPoolSemaphore {
  17. private final static int POOL_SIZE = 10;
  18. // 两个指示器,分别表示池子还有可用连接和已用连接
  19. private final Semaphore useful;
  20. private final Semaphore useless;
  21. // 存放数据库连接的容器
  22. private static LinkedList<Connection> pool = new LinkedList<Connection>();
  23. // 初始化池
  24. static {
  25. for (int i = 0; i < POOL_SIZE; i++) {
  26. pool.addLast(SqlConnectImpl.fetchConnection());
  27. }
  28. }
  29. public DBPoolSemaphore() {
  30. this.useful = new Semaphore(10);
  31. this.useless = new Semaphore(0);
  32. }
  33. /**
  34. * 归还连接
  35. */
  36. public void returnConnect(Connection connection) throws InterruptedException {
  37. if (connection != null) {
  38. System.out.println("当前有" + useful.getQueueLength() + "个线程等待数据库连接!!"
  39. + "可用连接数:" + useful.availablePermits());
  40. useless.acquire();
  41. synchronized (pool) {
  42. pool.addLast(connection);
  43. }
  44. useful.release();
  45. }
  46. }
  47. /**
  48. * 从池子拿连接
  49. */
  50. public Connection takeConnect() throws InterruptedException {
  51. useful.acquire();
  52. Connection connection;
  53. synchronized (pool) {
  54. connection = pool.removeFirst();
  55. }
  56. useless.release();
  57. return connection;
  58. }
  59. }
  60. /**
  61. * 测试代码
  62. */
  63. public class AppTest {
  64. private static DBPoolSemaphore dbPool = new DBPoolSemaphore();
  65. private static class BusiThread extends Thread {
  66. @Override
  67. public void run() {
  68. // 让每个线程持有连接的时间不一样
  69. Random r = new Random();
  70. long start = System.currentTimeMillis();
  71. try {
  72. Connection connect = dbPool.takeConnect();
  73. System.out.println("Thread_" + Thread.currentThread().getId()
  74. + "_获取数据库连接共耗时【" + (System.currentTimeMillis() - start) + "】ms.");
  75. //模拟业务操作,线程持有连接查询数据
  76. Thread.sleep(100 + r.nextInt(100));
  77. System.out.println("查询数据完成,归还连接!");
  78. dbPool.returnConnect(connect);
  79. } catch (InterruptedException e) {
  80. e.printStackTrace();
  81. }
  82. }
  83. }
  84. public static void main(String[] args) {
  85. for (int i = 0; i < 50; i++) {
  86. Thread thread = new BusiThread();
  87. thread.start();
  88. }
  89. }
  90. }

当然,你也可以使用一个 semaphore 来实现,不过需要注意的是 semaphore 的初始数量为10并不是固定的,如果你后面归还连接时 dbPool.returnConnect(new SqlConnectImpl()); 的话,那么他的数量会变成 11 。

五、Exchange

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

但是这种只能在两个线程种传递,适用面过于狭窄。

六、Callable、Future、FutureTask

  • Runnable 是一个接口,在它里面只声明了一个 run()方法,由于 run()方法返回值为 void 类型,所以在执行完任务之后无法返回任何结果。
  • Callable 位于 java.util.concurrent 包下,它也是一个接口,在它里面也只声明了一个方法,只不过这个方法叫做 call(),这是一个泛型接口,call()函数返回的类型就是传递进来的 V 类型。
  • Future 就是对于具体的 Runnable 或者 Callable 任务的执行结果进行取消、查询是否完成、获取结果。必要时可以通过 get 方法获取执行结果,该方法会阻塞直到任务返回结果。
  • FutureTask 因为 Future 只是一个接口,所以是无法直接用来创建对象使用的,因此就有了 FutureTask 。

关系图示:

图片

所以,我们可以通过 FutureTask 把一个 Callable 包装成 Runnable,然后再通过这个 FutureTask 拿到 Callable 运行后的返回值。

示例代码:

  1. public class FutureTaskTest {
  2. private static class CallableTest implements Callable<Integer> {
  3. private int sum = 0;
  4. @Override
  5. public Integer call() throws Exception {
  6. System.out.println("Callable 子线程开始计算!");
  7. for (int i = 0; i < 5000; i++) {
  8. if (Thread.currentThread().isInterrupted()) {
  9. System.out.println("Callable 子线程计算任务中断!");
  10. return null;
  11. }
  12. sum = sum + i;
  13. System.out.println("sum=" + sum);
  14. }
  15. System.out.println("Callable 子线程计算结束!结果为: " + sum);
  16. return sum;
  17. }
  18. }
  19. public static void main(String[] args) throws ExecutionException, InterruptedException {
  20. CallableTest callableTest = new CallableTest();
  21. // 包装
  22. FutureTask<Integer> futureTask = new FutureTask<>(callableTest);
  23. new Thread(futureTask).start();
  24. Random r = new Random();
  25. if (r.nextInt(100) > 50) {
  26. // 如果r.nextInt(100) > 50则计算返回结果
  27. System.out.println("sum = " + futureTask.get());
  28. } else {
  29. // 如果r.nextInt(100) <= 50则取消计算
  30. System.out.println("Cancel...");
  31. futureTask.cancel(true);
  32. }
  33. }
  34. }

发表评论

表情:
评论列表 (有 0 条评论,201人围观)

还没有评论,来说两句吧...

相关阅读

    相关 线并发工具

    Fork-Join 什么是分而治之? 规模为N的问题,N<阈值,直接解决,N>阈值,将N分解为K个小规模子问题,子问题互相对立,与原问题形式相同,将子问题的解合并得到