Why is threading works on a single core CPU?

[亡魂溺海] 提交于 2019-12-22 09:16:01

问题


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 if I run Thread.sleep(5000) and Thread.sleep(1000) sequentially in main Thread, the time consumed would be 6 sec, but since I am using Threading, it would only cost 5 sec on a multicore CPU machine, and it did. But my question is:

Why is the result still 5 sec on a single core CPU machine? Of course Threading is used, but isn't it just simulated threading by time division multiplexing?

My understanding of time division multiplexing is: assume Thread.sleep(5000) is task A, and Thread.sleep(1000) is task B, and we could break it apart to be : A1, A2, A3 ; B1, B2

Sequential is just : A1, A2, A3, B1, B2

Time division Multiplexing Threading is just: A1, B1, A2, B2, A3

If it is, how come the first costs 6 seconds, and the 2nd only 5?

Am I way of base here?


回答1:


The result is 5, not 6, because the two threads can sleep simultaneously. Going to sleep by calling Thread.sleep() lets the other thread run, but the remaining sleep interval timer continues ticking for both threads.

Note that this applies only to sleeping (which uses nearly zero CPU), but not to doing useful work: in this case the timing on a single-core non-hyperthreaded CPU would indeed be additive. For example, if one thread needed to do five seconds worth of number crunching, and the other needed to do a second worth of number crunching, the total time for both threads would be six seconds.




回答2:


By calling Thread.sleep(sleeptime), the Thread signals that it doesn't need the CPU for at least 'sleeptime' millis.

In the meantime the other thread can be executed.



来源:https://stackoverflow.com/questions/16591444/why-is-threading-works-on-a-single-core-cpu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!