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?