使用 java.util.concurrent 触发并忘记
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18643477/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Fire and forget with java.util.concurrent
提问by Philippe Blayo
How to go about implementing a "fire and forget" behavior with java.util.concurrency? I tried:
如何使用 java.util.concurrency实现“即发即弃”行为?我试过:
ExecutorService executor = Executors.newSingleThreadExecutor();
public void push(Callable<Boolean> task) {
Future<Boolean> future = executor.submit(task);
future.get(timeout, timeoutUnit);
}
but the get()
is blocking until completion. The push()
caller is not interested in the result of the task.
但get()
阻塞直到完成。该push()
来电者未在任务的结果感兴趣。
采纳答案by Sotirios Delimanolis
Don't call get()
. submit()
is enough to start the Callable
in a Thread
. You can pass around the Future
and call its get()
when you are ready to get the result (if ever).
不要打电话get()
。submit()
足以Callable
在 a 中启动Thread
。当您准备好获得结果(如果有的话)时,您可以传递它Future
并调用它get()
。
The Javadocstates
该的Javadoc状态
Submits a value-returning task for execution and returns a Future representing the pending results of the task. The Future's get method will return the task's result upon successful completion.
If you would like to immediately block waiting for a task, you can use constructions of the form result = exec.submit(aCallable).get();
提交一个返回值的任务以供执行,并返回一个表示任务未决结果的 Future。Future 的 get 方法将在成功完成后返回任务的结果。
如果您想立即阻止等待任务,可以使用 result = exec.submit(aCallable).get(); 形式的结构。
So just don't call get()
.
所以不要打电话get()
。
回答by leoismyname
dont need the future object if you have to forget it i.e. dont care about the future of the thread. :)
如果您必须忘记它,则不需要未来对象,即不关心线程的未来。:)
ExecutorService executor = Executors.newSingleThreadExecutor();
public void push(Callable<Boolean> task) {
executor.submit(task);
}
or if you need to use future some time later than :-
或者如果您需要在以后的某个时间使用 future :-
ExecutorService executor = Executors.newSingleThreadExecutor();
public void push(Callable<Boolean> task) {
someCollection.add(executor.submit(task)); // use futures later
}
or just use execute from Executor and pass Runnable, if you dont intent to get the future at all.
或者只是使用从 Executor 执行并传递 Runnable,如果您根本不打算获得未来。
ExecutorService executor = Executors.newSingleThreadExecutor();
public void push(Runnable task) {
executor.execute(task);
}
// execute will invoke default exceptional handler in case of exception, that can be lost in case if you dont get hold of futures in submit method.
// 如果发生异常,execute 将调用默认的异常处理程序,如果您没有在 submit 方法中获取期货,则可能会丢失该处理程序。