I am trying to understand how java threads works with CPU cores. I have a 4 core CPU and when I try to run below codes execution times are interesting. Why it doesn't speed up with multiple threads? Am I doing something wrong?
availableProcessors() returns 4 by the way.
Below code takes nearly 27 seconds;
Runnable runnable = new Runnable() {
@Override
public void run() {
int x = 0;
while(x < 10000000){
System.out.println(x);
x++;
}
}
};
Thread t1 = new Thread(runnable);
t1.start();
When I use multiple threads it takes 33 seconds;
Runnable runnable = new Runnable() {
@Override
public void run() {
int x = 0;
while(x < 5000000){
System.out.println(x);
x++;
}
}
};
Runnable runnable2 = new Runnable() {
@Override
public void run() {
int x = 5000000;
while(x < 10000000){
System.out.println(x);
x++;
}
}
};
Thread t1 = new Thread(runnable);
t1.start();
Thread t2 = new Thread(runnable2);
t2.start();