我喜欢在线程池中使用流来控制线程的执行。
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中获取String的工作方法。
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>
1条答案
按热度按时间n8ghc7c11#
一旦代码错误被修复(
str
=〉s
),代码就可以很好地编译和运行。公共池
自定义池
如果编译器像问题中描述的那样抱怨,你需要通过在第三行转换lambda表达式来帮助它选择正确的
submit()
重载:单线程