Lets we have following code(we will run it on single core CPU):
Runnable runnable1 = new Runnable() {
@Override
public void run() {
System.out.println("runnable_1_1");
System.out.println("runnable_1_2");
}
};
Runnable runnable2 = new Runnable() {
@Override
public void run() {
System.out.println("runnable_2_1");
System.out.println("runnable_2_2");
}
};
ExecutorService executorService = Executors.newSingleThreadExecutor(); // or Executors.newCachedThreadExecutor();
executorService.execute(runnable1);
executorService.execute(runnable2);
executorService.shutdown();
Is it theoretically possible that one task will be wedged to another and we will see output like this:
runnable_1_1
runnable_2_1
runnable_2_2
runnable_1_2
Single thread executor is not mandatory for this example. Mandatory that we have only one CPU core
This cannot be cleanly done on Java level for an arbitrary thread, as there are no non-deprecated methods to suspend it. All valid methods of control include the thread actively yielding.
However operating system itself normally has a scheduler that periodically suspends and resumes all running processes, allowing to have much more of them than the number of CPU cores available. Also, Java virtual machine normally does not run just as a single process (green threads belong to the past), there is one process per thread.
As a result, the operating system may suspend one thread for a short time, allowing to run another thread, or some other process outside Java virtual machine. The general answer is likely yes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With