javamultithreadingparallel-processing

Java threads are not actually executed in parallel?


Until now I was under the impression that 2 threads that start in the same time are also executed in parallel (both running their piece of codes in the same time), but I read some documentation recently and I understood that they actually take turns on the execution of their code, so there is no piece of code for first thread executed in the same time as a piece of code from the second thread. Is my understanding correct?

If yes, then how multi-threading is faster then one thread execution? I'm asking this because the only difference is that a single thread executes the code sequential, while multithreading can take turns on the execution, but still should take the same amount of time since it's nothing done in parallel


Solution

  • a) on multi-processor machines, threads can actually run in parallel (one per CPU)

    b) If your thread calls Thread.sleep() while waiting for IO etc., it makes resources available to other threads. So multi-threaded applications are actually faster than single-threaded ones when dealing with external resources