在java中为平台线程池创建单独的线程库

nafvub8i  于 2024-01-05  发布在  Java
关注(0)|答案(2)|浏览(165)

我想创建一个虚拟线程池,运行在单独的Java线程池上。
以下是我试图创建的架构:
x1c 0d1x的数据
这是为了使我能够创建单独的池来在一个JVM中运行批处理任务,并利用每个池的n:mMap的虚拟线程。因此,如果我有12个核心,那么我可以创建2个6线程的线程池。每个池将只执行特定的任务。每个池将有N个VirtualThreads。因此,这里的Map将是2个{N VirtualThreads -> 6 Platform Threads}的池。
TLDR,我想限制虚拟线程池可以运行的PlatformThreads的数量。
我能想到的一件事是,创建线程池,当传入一个runnable时,在run方法中,我可以只创建虚拟线程,但不确定它有多实用,我是否会得到我想要的池分区。这种方法的另一个问题是,虚拟线程将在一个java线程中运行,所以没有N:MMap。

kninwzqo

kninwzqo1#

Virtual threads的发明是为了避免你似乎正在承担的麻烦。
而且,虚拟线程被明确地记录为 * 不 * 用于池化。像facial tissues一样,抓取一个新的,使用它,然后释放。
阅读Java JEP,并与罗恩Pressler,Alan Bateman,José Paumard等一起观看视频,以了解虚拟线程技术的目的和性质。
你说:
我的用例使用相互依赖的作业(基本上一个作业的输出为队列中的另一个作业提供输入)。
.和:
当传入一个runnable时,在run方法中,我可以创建虚拟线程
把你的想法从里到外:与其创建虚拟线程来运行一堆相关的级联任务,不如只创建一个线程来以串行方式完成所有工作。
如果你有一系列级联任务,每个任务都在前一个任务的结果之后执行,那么只需将所有工作写入一个Runnable/Callable。在一个新的虚拟线程中执行该单个组合任务。让该虚拟线程运行完成。
让我们设计一个简单的演示应用程序。我们有三个任务,TaskATaskBTaskC。它们被放在一起作为AlphabetTask。结果是“ABC”,每个字母都被每个子任务添加。

  1. class AlphabetTask implements Callable < String >
  2. {
  3. private final UUID id = UUID.randomUUID ( );
  4. @Override
  5. public String call ( ) throws Exception
  6. {
  7. System.out.println ( "Starting AlphabetTask " + this.id + " " + Instant.now ( ) );
  8. String a = new TaskA ( ).call ( );
  9. String b = new TaskB ( a ).call ( );
  10. String c = new TaskC ( b ).call ( );
  11. System.out.println ( "Ending AlphabetTask " + this.id + " Result: " + c + " " + Instant.now ( ) );
  12. return c;
  13. }
  14. }
  15. class TaskA implements Callable < String >
  16. {
  17. @Override
  18. public String call ( ) throws Exception
  19. {
  20. System.out.println ( "Running TaskA. " + Instant.now ( ) );
  21. Thread.sleep ( Duration.ofMillis ( ThreadLocalRandom.current ( ).nextInt ( 100 , 800 ) ) );
  22. return "A";
  23. }
  24. }
  25. class TaskB implements Callable < String >
  26. {
  27. private final String input;
  28. public TaskB ( final String input )
  29. {
  30. this.input = input;
  31. }
  32. @Override
  33. public String call ( ) throws Exception
  34. {
  35. System.out.println ( "Running TaskB. " + Instant.now ( ) );
  36. Thread.sleep ( Duration.ofMillis ( ThreadLocalRandom.current ( ).nextInt ( 100 , 800 ) ) );
  37. return this.input + "B";
  38. }
  39. }
  40. class TaskC implements Callable < String >
  41. {
  42. private final String input;
  43. public TaskC ( final String input )
  44. {
  45. this.input = input;
  46. }
  47. @Override
  48. public String call ( ) throws Exception
  49. {
  50. System.out.println ( "Running TaskC. " + Instant.now ( ) );
  51. Thread.sleep ( Duration.ofMillis ( ThreadLocalRandom.current ( ).nextInt ( 100 , 800 ) ) );
  52. return this.input + "C";
  53. }
  54. }

字符串
我们创建了三个 AlphabetTask 的示例。

  1. Collection < AlphabetTask > alphabetTasks =
  2. List.of (
  3. new AlphabetTask ( ) ,
  4. new AlphabetTask ( ) ,
  5. new AlphabetTask ( )
  6. );


我们将所有这些示例提交给executor服务。对于这三个AlphabetTasks,executor都会分配一个新的虚拟线程。在每个虚拟线程中,我们的每个子任务都会按顺序调用。
注意,如果executor服务的任务在一天内完成,我们可以使用try-with-resources语法自动关闭它。

  1. List < Future < String > > futures = List.of ( );
  2. try (
  3. ExecutorService executorService = Executors.newVirtualThreadPerTaskExecutor ( ) ;
  4. )
  5. {
  6. try
  7. {
  8. futures = executorService.invokeAll ( alphabetTasks );
  9. } catch ( InterruptedException e )
  10. {
  11. throw new RuntimeException ( e );
  12. }
  13. }
  14. // The try-with-resources blocks here if executor service has any uncompleted tasks.
  15. futures.forEach ( stringFuture -> {
  16. try
  17. {
  18. System.out.println ( stringFuture.get ( ) );
  19. } catch ( InterruptedException | ExecutionException e )
  20. {
  21. throw new RuntimeException ( e );
  22. }
  23. } );


警告:虚拟线程适用于代码涉及阻塞的任务,如文件I/O,网络I/O,数据库调用,等待锁等。不要使用虚拟线程来运行CPU绑定的任务,如视频编码(不涉及阻塞)。
运行时:

  1. Starting AlphabetTask 3a594ed1-a76e-4927-83b1-2d6bc81f566c 2023-12-03T20:30:03.442091Z
  2. Starting AlphabetTask 12743216-8e42-4be1-bfc4-1893e08e58a7 2023-12-03T20:30:03.442091Z
  3. Starting AlphabetTask 94a4d5b9-3ed9-43d4-ba66-509380fa9f8b 2023-12-03T20:30:03.442091Z
  4. Running TaskA. 2023-12-03T20:30:03.452388Z
  5. Running TaskA. 2023-12-03T20:30:03.452392Z
  6. Running TaskA. 2023-12-03T20:30:03.452383Z
  7. Running TaskB. 2023-12-03T20:30:03.556780Z
  8. Running TaskB. 2023-12-03T20:30:03.687342Z
  9. Running TaskC. 2023-12-03T20:30:03.812744Z
  10. Running TaskB. 2023-12-03T20:30:04.108820Z
  11. Running TaskC. 2023-12-03T20:30:04.278596Z
  12. Ending AlphabetTask 94a4d5b9-3ed9-43d4-ba66-509380fa9f8b Result: ABC 2023-12-03T20:30:04.310085Z
  13. Running TaskC. 2023-12-03T20:30:04.360861Z
  14. Ending AlphabetTask 3a594ed1-a76e-4927-83b1-2d6bc81f566c Result: ABC 2023-12-03T20:30:04.624803Z
  15. Ending AlphabetTask 12743216-8e42-4be1-bfc4-1893e08e58a7 Result: ABC 2023-12-03T20:30:04.953132Z
  16. ABC
  17. ABC
  18. ABC


注意:当跨线程调用System.out.println时,控制台上的输出可能 * 不 * 按时间顺序出现。如果你关心顺序,请包括并检查时间戳。
为了方便您的复制粘贴,下面是所有这些代码,它们将被放入一个.java文件中。

  1. package work.basil.example.threading;
  2. import java.time.Duration;
  3. import java.time.Instant;
  4. import java.util.Collection;
  5. import java.util.List;
  6. import java.util.UUID;
  7. import java.util.concurrent.*;
  8. public class Subtasks
  9. {
  10. public static void main ( String[] args )
  11. {
  12. Subtasks app = new Subtasks ( );
  13. app.demo ( );
  14. }
  15. private void demo ( )
  16. {
  17. Collection < AlphabetTask > alphabetTasks =
  18. List.of (
  19. new AlphabetTask ( ) ,
  20. new AlphabetTask ( ) ,
  21. new AlphabetTask ( )
  22. );
  23. List < Future < String > > futures = List.of ( );
  24. try (
  25. ExecutorService executorService = Executors.newVirtualThreadPerTaskExecutor ( ) ;
  26. )
  27. {
  28. try
  29. {
  30. futures = executorService.invokeAll ( alphabetTasks );
  31. } catch ( InterruptedException e )
  32. {
  33. throw new RuntimeException ( e );
  34. }
  35. }
  36. // The try-with-resources blocks here if executor service has any uncompleted tasks.
  37. futures.forEach ( stringFuture -> {
  38. try
  39. {
  40. System.out.println ( stringFuture.get ( ) );
  41. } catch ( InterruptedException | ExecutionException e )
  42. {
  43. throw new RuntimeException ( e );
  44. }
  45. } );
  46. }
  47. }
  48. class AlphabetTask implements Callable < String >
  49. {
  50. private final UUID id = UUID.randomUUID ( );
  51. @Override
  52. public String call ( ) throws Exception
  53. {
  54. System.out.println ( "Starting AlphabetTask " + this.id + " " + Instant.now ( ) );
  55. String a = new TaskA ( ).call ( );
  56. String b = new TaskB ( a ).call ( );
  57. String c = new TaskC ( b ).call ( );
  58. System.out.println ( "Ending AlphabetTask " + this.id + " Result: " + c + " " + Instant.now ( ) );
  59. return c;
  60. }
  61. }
  62. class TaskA implements Callable < String >
  63. {
  64. @Override
  65. public String call ( ) throws Exception
  66. {
  67. System.out.println ( "Running TaskA. " + Instant.now ( ) );
  68. Thread.sleep ( Duration.ofMillis ( ThreadLocalRandom.current ( ).nextInt ( 100 , 800 ) ) );
  69. return "A";
  70. }
  71. }
  72. class TaskB implements Callable < String >
  73. {
  74. private final String input;
  75. public TaskB ( final String input )
  76. {
  77. this.input = input;
  78. }
  79. @Override
  80. public String call ( ) throws Exception
  81. {
  82. System.out.println ( "Running TaskB. " + Instant.now ( ) );
  83. Thread.sleep ( Duration.ofMillis ( ThreadLocalRandom.current ( ).nextInt ( 100 , 800 ) ) );
  84. return this.input + "B";
  85. }
  86. }
  87. class TaskC implements Callable < String >
  88. {
  89. private final String input;
  90. public TaskC ( final String input )
  91. {
  92. this.input = input;
  93. }
  94. @Override
  95. public String call ( ) throws Exception
  96. {
  97. System.out.println ( "Running TaskC. " + Instant.now ( ) );
  98. Thread.sleep ( Duration.ofMillis ( ThreadLocalRandom.current ( ).nextInt ( 100 , 800 ) ) );
  99. return this.input + "C";
  100. }
  101. }


你说:
所以如果我有12个核心,那么我可以创建6个线程的2个线程。
你并不像你所相信的那样拥有那么多的控制权。哪些平台线程在哪个内核上运行,在什么时间运行多长时间,完全取决于主机操作系统。调度行为根据计算机上的当前负载而随时变化。在任何时候,都可能没有、很少或所有线程正在执行。

展开查看全部
p8ekf7hl

p8ekf7hl2#

你的方法不对。
您真正想要做的似乎是 * 限制某些类型任务的并发性 *,也就是说,您最多需要M1个第一类任务(称之为A任务)能够并发运行,第二类任务最多M2(称之为B任务)但是试图创建绑定到平台线程池的虚拟线程池是在错误的级别上解决这个问题。
如果你想限制一个给定活动的并发性,合适的工具是一个信号量。为每种任务A和B创建一个信号量。A任务需要A信号量的许可; B任务需要来自B信号量的许可。用信号量的获取-释放来 Package 任务是微不足道的,所以如果你愿意,你可以把它作为提交逻辑的一部分,而不是任务业务逻辑的一部分。每个任务都在一个虚拟线程中运行。
你可能会想:“但是我可能会有很多虚拟线程在等待A信号量。”是的,您可能会这样做。但是您不在乎;它们很便宜。为每个任务创建一个虚拟线程,并且不要尝试将它们池化。(这也意味着您不需要单独的平台线程池。)

相关问题