在文档中,Dart 是单线程的,但为了一次执行两个操作,我们使用与线程相同的 future 对象。
Use Future objects (futures) to perform asynchronous operations.
如果 Dart 是单线程的,那么为什么它允许执行异步操作。
注意:异步操作是称为线程的并行操作
最佳答案
你提到过:
Asynchronous operations are parallel operations which are called threads
首先,异步操作不是完全并行的,甚至不是并发的。它只是意味着我们不想阻塞我们的执行流程(线程)或等待响应直到某些工作完成。但是我们实现异步操作的方式可以决定是并行还是并发。
并行与并发?
Parallelism is actually doing lots of things simultaneously at the same time. ex - You are walking and at the same time you're digesting you food. Both tasks are completely running parallel and exactly at the same time.
虽然
Concurrency is the illusion of Parallelism.Tasks seems to be Executed parallel but they aren't. It like handing lots of things at a time but only doing one task at a specific time. ex - You are walking and suddenly stop to tie your show lace. After tying your shoe lace you again start walking.
现在来到 Dart,Future
对象以及 async
和 await
关键字用于执行异步任务。这里异步并不意味着任务将彼此并行或并发执行。相反,在 Dart 中,甚至异步任务都在同一个线程上执行,这意味着当我们等待另一个任务完成时,我们将继续执行我们的同步代码。 Future
对象用于表示将来某个时间将要完成的任务的结果。
如果您想真正并发执行任务,请考虑使用 Isolates(它在单独的线程中运行并且不与主线程(或生成线程)共享内存。
关于multithreading - Dart 是单线程的,但为什么它使用 Future Objects 并执行异步操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53019756/