I wanted to measure, how long 2 different programs need to perform 1 task. One program used threads, the other didn’t.The task was to count up to 2000000.
Class with threads:
public class Main {
private int res1 = 0;
private int res2 = 0;
public static void main(String[] args) {
Main m = new Main();
long startTime = System.nanoTime();
m.func();
long endTime = System.nanoTime();
long duration = endTime - startTime;
System.out.println("duration: " + duration);
}
public void func() {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 1000000; i++) {
res1++;
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 1000000; i < 2000000; i++) {
res2++;
}
}
});
t1.start();
t2.start();
System.out.println(res1 + res2);
}
}
Class without threads:
public class Main {
private int res = 0;
public static void main(String[] args) {
Main m = new Main();
long startTime = System.nanoTime();
m.func();
long endTime = System.nanoTime();
long duration = endTime - startTime;
System.out.println("duration: " + duration);
}
public void func() {
for (int i = 0; i < 2000000; i++) {
res++;
}
System.out.println(res);
}
}
After 10 measurement the average results (in nanoseconds) were:
With threads: 1952358
Without threads: 7941479
Am I doing it right?
How come, with 2 threads it’s 4x faster and not only 2x?
In the lines
you are starting the thread execution, but you aren’t actually waiting for them to finish before you take your time measurement. To wait until the threads are finished, call
The join method will block until the thread is finished. Then measure the execution time.