简体   繁体   English

Java / Guava中的异步编程

[英]Asynchronous programming in Java/Guava

class A{
    final B; 

    B.compute(); // Does executing this line create a new thread since this returns
    // a future and the entire function is executed by the same thread ?


    }

    class B{

    Future<Void> compute(){

    C obj = factoryOfC.getC();

    ListenableFuture<Void> future = executorService.submit (new Callable(){
        doSomething();
    });

    Futures.addCallback(future, new FutureCallback<Void>(){
        @Override
        void onSuccess(){
        }
        @Override
        void onFailure(){
        }

    } // end of callback. 
} // end of class B

How would you define a unit of work here ? 您如何在这里定义工作单元? Which thread/s will be doing which unit of work ? 哪个线程将执行哪个工作单元? Would the callable and callback be executed in the same thread ? 可以在同一线程中执行callable和callback吗?

WILL obj of type C be executed by the same thread ? C类型的obj是否将由同一线程执行?

Have you run it to see what it does? 您是否运行过以查看其作用? I doubt it because what you've provided won't compile. 我对此表示怀疑,因为您提供的内容无法编译。

Have you read the JavaDoc for the methods you are calling? 您是否已阅读要调用的方法的JavaDoc? The answers are there. 答案在那里。

You submit a Callable to ExecutorService.submit() . 您将Callable提交给ExecutorService.submit() The documentation for Executor says: Executor的文档说:

The command may execute in a new thread, in a pooled thread, or in the calling thread, at the discretion of the Executor implementation 该命令可以根据执行程序的执行情况在新线程,池线程或调用线程中执行

... and the documentation for ExecutorService adds no specifics; ...并且ExecutorService的文档未添加任何细节; meaning that as a programmer all you know is that you've requested that this be run in some thread, some time in future. 这意味着作为程序员,您所知道的就是您已要求在将来的某个时间在某个线程中运行它。

But you have a Future object that acts as a handle on the promised execution of your task. 但是您有一个Future对象,该对象充当所承诺的任务执行的句柄。 You use Futures.addCallback() to request that some work is performed when the task completes. 您使用Futures.addCallback()请求在任务完成时执行一些工作。 In what thread will this work run? 这项工作将在哪个线程运行?

The JavaDoc for Futures.addCallback() says: JavaDoc for Futures.addCallback()表示:

  • If the input Future is done at the time addCallback is called, addCallback will execute the callback inline. 如果在调用addCallback时完成了Future的输入,则addCallback将内联执行回调。
  • If the input Future is not yet done, addCallback will schedule the callback to be run by the thread that completes the input Future, which may be an internal system thread such as an RPC network thread. 如果输入Future尚未完成,则addCallback将安排由完成输入Future的线程运行的回调,该线程可能是内部系统线程,例如RPC网络线程。

Not the execution of the line B.compute(); 不执行B.compute(); alone creates a new thread; 单独创建一个新线程; the line executorService.submit submits a new Callable to the ExecutorService which runs in a new thread. executorService.submit行将新的Callable提交到在新线程中运行的ExecutorService

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM