Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is threading works on a single core CPU?

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?

like image 795
Will Avatar asked Dec 11 '22 15:12

Will


2 Answers

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.

like image 165
Sergey Kalinichenko Avatar answered Dec 31 '22 14:12

Sergey Kalinichenko


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.

like image 34
mschenk74 Avatar answered Dec 31 '22 16:12

mschenk74