简体   繁体   English

Java中的单线程异步处理

[英]Single-Thread asynchronous processing in Java

I have a question about Java threading. 我有一个关于Java线程的问题。 Is possible run two tasks asynchronously when I use only Main Thread? 当我只使用主线程时,是否可以异步运行两个任务? I read this article: Asynchronous vs synchronous execution, what does it really mean? 我读过这篇文章: 异步与同步执行,它到底意味着什么? Second answer says that is possible case where is only one thread (not main thread and one other) and tasks are executed asynchronously. 第二个答案说,可能的情况是只有一个线程(不是主线程和另一个线程),并且任务是异步执行的。 I think that it is not possible in Java because exists only one flow of control. 我认为在Java中是不可能的,因为只存在一个控制流。 I think that in Java each task need own thread for execution tasks asynchronously. 我认为在Java中,每个任务都需要异步执行任务的自己的线程。

Short answer: yes. 简短回答:是的。 This is actually a common feature of non-blocking I/O. 这实际上是非阻塞I / O的常见功能。 Java has a non-blocking I/O library - you can see more details about it here . Java有一个非阻塞的I / O库 - 你可以在这里看到更多关于它的细节。 (I'm truthfully not aware of all of the implementation details of the library, though, so I'm not sure if there's a guarantee that it won't create extra threads). (我实际上并不知道库的所有实现细节,所以我不确定是否保证它不会创建额外的线程)。 This is a notable feature of Node.js, for example, and the .NET Framework has this feature available as well. 例如,这是Node.js的一个显着特性,.NET Framework也具有此功能。

Here's an analogy to illustrate the difference between single-threaded asynchronous programming and multithreading: suppose that you go to a restaurant with a group of 10 people. 这里有一个类比来说明单线程异步编程和多线程之间的区别:假设你去一个有10人团队的餐馆。 When the waiter asks the first person to order, he's not ready yet. 当服务员要求第一个人订购时,他还没准备好。 In "ordinary" single-threaded programming with blocking I/O, the waiter waits until he's ready before moving on to anyone else. 在具有阻塞I / O的“普通”单线程编程中,服务员等到他准备好之后才转移到其他任何人。 In multithreading, you could bring in a second waiter to wait for him. 在多线程中,你可以带第二个服务员等他。 In asynchronous/non-blocking I/O, you simply move on to the next person in the group and come back to the first guy when he's ready. 在异步/非阻塞I / O中,您只需转移到组中的下一个人,并在他准备好时回到第一个人。

Obviously, I'm glossing over a lot of the subtleties here, but hopefully that illustrates the difference to some degree. 显然,我正在掩饰这里的许多微妙之处,但希望这在某种程度上说明了这种差异。

For more information, see: 有关更多信息,请参阅:

Does an asynchronous call always create/call a new thread? 异步调用是否始终创建/调用新线程?

Asynchronous processing with a single thread 使用单个线程进行异步处理

There is no thread (focuses on C#) 没有线程 (专注于C#)

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

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