0

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");
    }
}
  • For one, you're not [testing correctly](https://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java) and secondly you're assuming that multithreading automatically makes everything faster. It's not that easy, you have to know when and if multithreading is an improvement or not. – Kayaman Nov 14 '20 at 10:12
  • @Kayaman can you kindly elaborate on your point – var2010 Nov 14 '20 at 10:35
  • Which point, the testing correctly or thinking that multithreading means everything is faster? – Kayaman Nov 14 '20 at 10:35
  • Multithreading means everything faster and where I am going wrong in my program. – var2010 Nov 14 '20 at 10:40
  • Well, multithreading is very difficult, so I suggest you read more and write less. I recommend the many other multithreading related questions on SO. You don't need to ask new questions (or write code when you don't understand multithreading yet). Reading and understanding is important. Not writing code blindly and asking "why isn't this fast?". – Kayaman Nov 14 '20 at 11:45
  • Thanks for your input ,I will surely go through the multi threading concepts. – var2010 Nov 14 '20 at 12:29

0 Answers0