从Lambda表达式返回值

从Lambda表达式返回值

本文介绍了如何从Lambda表达式返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个集合( concurrentHashMap )和一个应在单独的线程中工作并返回 numOfApples 的方法:

I have a collection (concurrentHashMap) and a method which should work in a separate thread and return numOfApples:

public int getApples(String treeNum) {
    int numOfApples = null;
    Runnable task = () -> {concurrentHashMap.get(treeNum).getApples(); };
    new Thread(task).start() ;
    return numOfApples;
}

是否可以将来自lambda表达式( concurrentHashMap.get(treeNum).getApples())的苹果传递给 numOfApples 变量?

Is it possible to pass num of apples from lambda expression (concurrentHashMap.get(treeNum).getApples()) to the numOfApples variable?

推荐答案

问题不在于从lambda表达式返回值.这是关于从异步任务返回结果.

The problem is not about returning the value from a lambda expression. It is about returning a result from an asynchronous task.

使用 可运行 .您应该使用 Callable 引用其Javadoc:

You won't be able to do that easily using a Runnable. You should use a Callable instead, quoting its Javadoc:

此外,您绝对不应创建这样的非托管原始线程: new Thread(task).start();.您应该使用 ExecutorService 并将 Callable 提交给它.

Also, you definitely should not be creating unmanaged raw threads like that: new Thread(task).start();. You should use an ExecutorService and submit the Callable to it.

考虑以下代码:

public int getApples(String treeNum) {
    Callable<Integer> task = () -> concurrentHashMap.get(treeNum).getApples();
    Future<Integer> future = Executors.newCachedThreadPool().submit(task);
    return future.get();
}

它将创建一个 Callable< Integer> ,其中包含返回苹果数量的任务.该任务被提交到 ExecutorService (我在这里只是使用了一个缓存的线程池,您可能想要另一个).结果包含在 Future< Integer> 实例中,该实例的 get()方法将阻塞,等待结果然后返回.

It creates a Callable<Integer> holding the task returning the number of apples. This task is submitted to an ExecutorService (I simply used a cached thread pool here, you might want another). The result is contained inside a Future<Integer> instance, whose get() method will block, wait for the result and then return it.

这篇关于如何从Lambda表达式返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 16:56