Reputation: 245
I have a question about Java threading. 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. I think that in Java each task need own thread for execution tasks asynchronously.
Upvotes: 8
Views: 5547
Reputation: 12181
Short answer: yes. This is actually a common feature of non-blocking I/O. Java has a non-blocking I/O library - you can see more details about it here. (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.
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. 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. In multithreading, you could bring in a second waiter to wait for him (or to take the other group members' orders). You could also bring in several waiters who each take the order of, for example, 2 or 3 group members. 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.
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#)
Upvotes: 10