I am just learning about multithreading by trying to create some little programs, and I found one specific thing I am not sure why it is the way it is.
I've two classes, they both count to 2 billion, and at the end they print out time it took them to do it. They are in separate files. The First one can do it in about 2 seconds (It would be faster but I am also doing other stuff there), and the new Thread(new Runnable())
in main class is much slower, it took about 8 seconds to do it.Can you explain why? Here is the code. Thank you.
public class First implements Runnable {
private long startTime, endTime;
public static double count = 0;
@Override
public void run() {
startTime = System.currentTimeMillis();
for (int count = 0; count <= 2000000000L; count++);
endTime = System.currentTimeMillis();
System.out.println(endTime - startTime); //it is done in about 2seconds
}
}
public class Threads {
public static void main(String[] args){
First f = new First();
f.run();
new Thread(new Runnable() {
@Override
public void run() {
long startTime, endTime;
double count;
startTime = System.currentTimeMillis();
for (count = 0; count < 2000000000L; count++)l
endTime = System.currentTimeMillis();
System.out.println(endTime - startTime); //about 8 seconds
}
}).start();
}
}
Update
Problem was on line 4, I did not realized that variable count is double, and on line 10, in for cycle I used int. Speed of incrementing the variables has nothing to do with threads, It is the problem of primitive data types as mentioned in comments down below.