Why does streaming work on one core processor?

To better understand Threading in Java, I wrote the following code

public class SimpleRunnableTest { public static void main(String[] args) throws InterruptedException { long start = System.currentTimeMillis(); Thread t1 = new Thread(new TT1()); t1.start(); Thread t2 = new Thread(new TT2()); t2.start(); t2.join(); t1.join(); long end = System.currentTimeMillis(); System.out.println("end-start="+(end-start)); } } class TT1 implements Runnable { public void run(){ try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } } } class TT2 implements Runnable { public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } 

The idea is that I sequentially execute Thread.sleep(5000) and Thread.sleep(1000) in main Thread, the time spent on consumption will be 6 sec , but since I use Threading, it will cost only 5 sec for multi-core processor machine, and thatโ€™s it. But my question is:

Why does the result remain 5 sec on a single-core CPU? Of course, Threading is used, but isn't it just simulated time-division multiplexing?

My understanding of time division multiplexing: suppose Thread.sleep(5000) is task A, and Thread.sleep(1000) is task B, and we can break it into parts: A1, A2, A3; B1, B2

The sequence is simple: A1, A2, A3, B1, B2

Time Division Multiplexing Thread only: A1, B1, A2, B2, A3

If so, then why does the first cost 6 seconds and the second only 5?

Am i here here?

+4
source share
2 answers

The result is 5, not 6, since two threads can sleep at the same time. Going to sleep when calling Thread.sleep() allows you to start another thread, but the remaining standby timer continues to tick for both threads.

Note that this only applies to sleep (which uses an almost zero CPU), but not in order to do useful work: in this case, synchronization on a single-core processor without a hyperthread would really be additive. For example, if one thread needed to crackle for five seconds, and the other needed to make a second value for the number of crunch, the total time for both threads would be six seconds.

+11
source

By calling Thread.sleep (sleeptime), Thread reports that it does not need a processor, at least for the "sleeptime" millis.

In the meantime, another thread may be executed.

+1
source

Source: https://habr.com/ru/post/1481202/


All Articles