【发布时间】:2017-08-11 23:42:23
【问题描述】:
我有一个异步 C++ 函数,它需要将工作传递给另一个线程,然后等待该工作完成。我使用std::promise 对象完成了这项工作,如下所示:
void task(std::function<void()> const& func) {
std::promise<void> promise;
//You can think of 'thread_pool' as being a wrapper around a std::vector<std::thread>
//where all the threads have a body that more-or-less look like
/* void run() {
* while(running) {
* task t;
* if(task_queue.try_pop(t)) t();
* }
* }
*/
thread_pool.post([&] {
try {
func();
promise.set_value();
} catch (...) {
promise.set_exception(std::current_exception());
}
});
promise.get_future().get();
}
所以我的问题是,在 Java 中表达相同概念的最简单方法是什么?在我的具体情况下,我需要管理 Swing 线程和 JavaFX 线程之间的通信,并管理两者之间的任务。这是我目前所拥有的:
public static void runAndWait(Runnable runner) {
Future<Object> future = new FutureTask<>(new Callable<Object>() {
public Object call() {
try {
runner.run();
} catch (RuntimeException e) {
//??? How do I report the exception to the future?
}
return null;
}
});
Platform.runLater(/*How do I run the future I've just created?*/);
future.get();//I want the exception to throw here if we caught one.
}
不过,很明显,我遗漏了一些东西。如何表达我用Java描述的C++代码?
【问题讨论】:
-
@Baummitaugen 为什么删除了 c++ 标签?回答这个问题需要熟悉问题前半部分中描述的 C++ 代码。
-
我会删除 c++ 代码,只包含你拥有的 java,描述你想要它做什么,以及它当前在做什么。那将是一个更高质量的问题
-
@Xirema 因为问题不在于 C++。对于诸如 “我如何在 C++ 中做 foo?” 之类的问题,它不会帮助任何人。纯粹是关于如何在 Java 中做 foo。
标签: java multithreading future