Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/326.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用流和可调用项的Java ThreadPoolExecutor_Java_Java Stream_Java.util.concurrent_Threadpoolexecutor - Fatal编程技术网

使用流和可调用项的Java ThreadPoolExecutor

使用流和可调用项的Java ThreadPoolExecutor,java,java-stream,java.util.concurrent,threadpoolexecutor,Java,Java Stream,Java.util.concurrent,Threadpoolexecutor,我有一个类实现了Callable,它有一个方法覆盖call,并返回Long 我创建了一个列表,其中包含可调用的,如下所示 List<Callable<Long>> callables = new ArrayList<>(); for (File fileEntry : folder.listFiles()) { callables.add(new DataProcessor(fileEntry)); 我打电话 threadPoolExecutor.i

我有一个类实现了
Callable
,它有一个方法覆盖
call
,并返回
Long

我创建了一个
列表
,其中包含
可调用的
,如下所示

List<Callable<Long>> callables = new ArrayList<>();
for (File fileEntry : folder.listFiles()) {
    callables.add(new DataProcessor(fileEntry));
我打电话

threadPoolExecutor.invokeAll(callables)
    .stream()
    .map(future -> {
        try {
            return future.get();
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
        })
        .collect(Collectors.toLong(/* what goes here? */));
我要做的是对来自
future.get()
的所有返回值求和


另外,由于我正在调用invokeAll,我是否仍然需要关闭执行器

您需要的是
收集器。summingLong

.collect(Collectors.summingLong(r -> r));
其中,
r->r
只是一个
tolong函数
,它从
可调用的
返回的每个
long
中生成一个
long

另外,由于我正在调用invokeAll,我是否仍然需要关闭执行器

ExecutorService.invokeAll
不会记录自动关闭。因此,您需要自己关闭它

您可以使用它来映射
未来。将
作为
长流
获取,然后找到流的

long sum = threadPoolExecutor.invokeAll(callables)
            .stream()
            .mapToLong(future -> {
                try {
                    return future.get();
                } catch (Exception e) {
                    throw new IllegalStateException(e);
                }
            }) // LongStream
            .sum(); // sum of the stream
注意:这使用
收集器简化了流API调用链。summingLong
。它允许在遍历集合时避免创建冗余的临时对象

旁白:您还可以
收集您的
可调用的
作为:

List<Callable<Long>> callables = fileList.stream()
                                         .map(fileEntry -> new DataProcessor(fileEntry))
                                         .collect(Collectors.toList());

谢谢。我想计算一下从invokeall到所有线程都完成需要多长时间。但如果我收集执行器关闭后的结束时间。它不会等待所有线程完成。@Mark您的意思是对所有可调用的计算时间进行基准测试吗?无法得到你所说的收集结束时间的确切含义。是的。确切地这就是我的意思
List<Callable<Long>> callables = fileList.stream()
                                         .map(fileEntry -> new DataProcessor(fileEntry))
                                         .collect(Collectors.toList());
System.out.println(threadPoolExecutor.isShutdown()); // would return false