【发布时间】:2021-08-29 07:22:55
【问题描述】:
我喜欢在使用带有线程池的流时控制线程执行。 目前我有 字符串列表
List<String> mylist = new ArrayList() {"1","2","3","4"}; //that holds the strings
List<Action> actions = new ArrayList<>{} holds function that manipulate the strings from mylist
每个动作都有从 mylist 中获取字符串的工作方法
Stream<String> stream = mylist.parallelStream();
stream = stream.flatMap(s-> actions.stream().map(ac -> ac.work(str)));
r = stream.collect(Collectors.toList());
一切都很好,但我无法控制线程池,知道我可以像这样使用 ForkJoinPool
Example
但我没有找到在我的示例中实现它的方法
例如,这不起作用:
ForkJoinPool customThreadPool = new ForkJoinPool(4);
r= customThreadPool.submit(
() -> mylist.parallelStream().flatMap(s-> actions.stream().map(ac -> ac.work(str))).collect(Collectors.toList()));
给我错误:
java: incompatible types: no instance(s) of type variable(s) T,R,A,capture#1 of ?,T exist so that java.util.concurrent.ForkJoinTask<T> conforms to java.util.List<java.lang.String>
谢谢
【问题讨论】:
-
不起作用是什么意思?你就是这样做的。
parallelStream()将使用来自customThreadPool的线程,而不是来自ForkJoinPool.commonPool()的线程,并且您可以完全控制customThreadPool。 -
语法中的某些东西已经磨损了,因为它给了我:')' 预期
-
不要在评论中显示错误。编辑问题并通过说明“不工作”的含义来澄清它。
-
当我添加时)它给了我:java:不兼容的类型:没有类型变量 T、R、A、capture#1 of ?,T 的实例存在,因此 java. util.concurrent.ForkJoinTask
符合 java.util.List -
r的类型是什么?看起来这可能是问题所在;您可能需要添加最终的.get()或.join()。
标签: java multithreading java-stream threadpool