I was trying to learn Multithreading,thought of doing an example on it.
As seen from code below first I am trying to initialise array with random numbers(Using single thread)
Next I am trying to fill the same array with random numbers using two threads.
However the single threaded block is running faster than the 2-threaded block. I am not able to understand why this is happening and somebody help me out on this.
Below is the code I am using:
import java.util.*;
public class MtRealExample{
public static void main(String[] args) throws Exception{
int[] a = new int[Integer.MAX_VALUE / 50];
Random r = new Random();
long startTime = System.currentTimeMillis();
for(int i = 0; i < a.length; i++){
a[i] = r.nextInt();
}
long endTime = System.currentTimeMillis();
System.out.println("Without Multithreading : " + (endTime - startTime) + "ms");
startTime = System.currentTimeMillis();
Thread t1 = new Thread(() -> {
for(int i = 0; i < a.length / 2; i++){
a[i] = r.nextInt();
}
});
Thread t2 = new Thread(() -> {
for(int i = a.length/2; i < a.length; i++){
a[i] = r.nextInt();
}
});
t1.start();
t2.start();
t1.join();
t2.join();
endTime = System.currentTimeMillis();
System.out.println("With Multithreading : " + (endTime - startTime) + "ms");
}
}