如何在不使用ExecutorService的情况下获取Future <MyObject>?

kro*_*old 15 java multithreading

我真的想做这样的事情:

 Callable<MyObject> myCallable = ....
 Future<MyObject> = new Thread( myCallable).start();
Run Code Online (Sandbox Code Playgroud)

我基本上想要启动一个与我的主要任务并行运行的长期运行的任务,并且我不希望池或线程重用.Executors的东西似乎非常集中,它需要我关闭池,所有这些都是我不想做的.

使用"Callable/Future"模式,因为我后来可能会引入Executors,但是就目前而言,它们只是开销.

有什么建议 ?

alp*_*ero 17

试试FutureTask.它没有对Executor框架的任何显式依赖,并且可以按原样实例化,或者您可以扩展它以对其进行自定义.


Jon*_*eet 14

好吧,你可以很容易地编写一个帮助方法:

public static Future<T> createFuture(Callable<T> callable)
{
    ExecutorService service = Executors.newSingleThreadExecutor();
    Future<T> ret = service.submit(callable);
    // Let the thread die when the callable has finished
    service.shutdown();
    return ret;
}
Run Code Online (Sandbox Code Playgroud)

编辑:要扩展alphazero的答案,你可以这样使用FutureTask:

FutureTask<MyObject> future = new FutureTask<MyObject>(myCallable);
new Thread(future).start(); // FutureTask implements Runnable
// Now use the future however you want
Run Code Online (Sandbox Code Playgroud)

是的,我会说这比我的第一个答案更好:)