How to implement several 'threads' running in only one thread How to implement several 'threads' running in only one thread multithreading multithreading

How to implement several 'threads' running in only one thread


I think you are confusing coroutines and green threads here.

Coroutines give up the control when they are ready to do it, without any interruption, so question about interruption is irrelevant here. Scala actors are implemented as coroutines.

Green threads are user-mode threads implemented by virtual machine without use of native OS capabilities. Obviously, virtual machine can insert any instructions into the code being executed in order to check whether it need to switch to another thread.


With actors it's simple, instead of using one thread per actor you use the same thread for executing messages for multiple actors. However, if an actor performs a blocking call or a heavy computation, another thread must be used to execute messages in other actors.

Green threads are light weight threads that can be implemented at the VM level. Green threads are always mapped to one or more OS threads. Synchronization and thread switching is handled in user space by the VM, which can significantly reduce overhead. However, there are drawbacks to green threads, for example IO calls might cause the thread to block and then the VM can't "reuse" the OS thread for another green thread and must instead use an additional OS thread.

Another solution is to use continuations, as implemented in the Scala compiler. The interruption and resuming of execution is then handled at the JVM bytecode level where local state is saved and restored. No VM support is needed.


Do you mean like tasks in an ExecutorService or ScheduledExecutorService in Java?

These tasks are added to a queue and preformed to completion. When one finishes another one starts. If you have a loop with a delay, you can use a repeating scheduled tasks instead. It complete for each iteration and allows another tasks to run.

If you want to know more details you might find reading the code interesting.