首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >什么时候使用异步计算?

什么时候使用异步计算?
EN

Stack Overflow用户
提问于 2015-01-07 09:08:41
回答 1查看 202关注 0票数 0

在异步计算中,我可以看到下面的例子:

代码语言:javascript
复制
//Create an Asynchronous channel. No connection has actually been established yet
 AsynchronousSocketChannel asynchronousSocketChannel = AsynchronousSocketChannel.open(); 

 /**Connect to an actual server on the given port and address. 
    The operation returns a   type of Future, the basis of the all asynchronous operations in java. In this case, a Void is returned because nothing is returned after a successful socket connection
     */
 Void connect = asynchronousSocketChannel.connect(new InetSocketAddress("127.0.0.1", 5000)).get();


 //Allocate data structures to use to communicate over the wire
 ByteBuffer helloBuffer = ByteBuffer.wrap("Hello !".getBytes()); 

 //Send the message

 Future<Integer> successfullyWritten=  asynchronousSocketChannel.write(helloBuffer);

  //Do some stuff here. The point here is that asynchronousSocketChannel.write() returns almost immediately, not waiting to actually finish writing the hello to the channel before returning control to the currently executing thread

 doSomethingElse();

 //now you can come back and check if it was all written (or not)

 System.out.println("Bytes written "+successfullyWritten.get());

我对异步计算很陌生。但我从您给出的示例中了解到,异步执行操作的全部目的是并行化操作。如果我们已经同步完成了一些事情,那么写()和doSomethingElse()就会依次发生。因此,选择异步计算的重要属性是:

1) doSomethingElse()不应依赖于write()的输出。

2)写()和doSomethingElse()都应该是耗时的步骤,否则并行化就没有意义了。对吗?

请纠正我,如果我的理解是错误的,有更多的东西,我们正在通过异步步骤的计算。

另外,请您提供一个使用异步计算的最常见的用例。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-01-07 09:12:43

是的,基本上您使用异步计算来处理与其他任务(例如ui线程)并行运行的耗时任务。然而,“耗时”的含义是一个定义问题,即在某些系统中,它可能意味着“超过几毫秒”。

例如,一些“耗时”任务可能会阻止您的ui顶部被更新,以便异步运行该任务,即与ui更新并行运行(例如,在Swing中,这意味着使用工作人员而不是在事件调度线程中执行这些任务)。

数据的可用性只是使用异步计算还是同步计算的一个次要指标。您可以将任务的执行推迟到所需的数据可用为止(例如,通过使用Future或消息),同时还可以执行其他计算(例如ui更新)。

也就是说,您应该仔细考虑如何建模任务,以减少开销(过多或太小的任务实际上可能会降低性能,不必要地阻塞CPU时间等资源)。如果数据的可用性实质上意味着同步计算,那么这可能是可行的。但是,您仍然可以有多个异步/并行进程,每个进程同步执行自己的任务。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27815847

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档