Search code examples
javamultithreadingconcurrency

Improve calculation time in parallel mode


I am new in the multithreading in Java, so I have a question about how to reduce calculation time in this example, without using Executors, Frameworks, etc, only plain threads?

public static void main(String[] args) throws TestException {

    Set<Double> res = new HashSet<>();

    for (int i = 0; i < TestConsts.N; i++) {
        res.addAll(TestCalc.calculate(i));
    }

    System.out.println(res);
}

And there is calculation method:

private static final Random rnd = new Random();

public static Set<Double> calculate(int num) throws TestException {
    // Emulates calculation delay time.
    try {
        Thread.sleep(rnd.nextInt(1000) + 1);
    }
    catch (InterruptedException e) {
        throw new TestException("Execution error.", e);
    }

    Set<Double> res = new HashSet<>();

    int n = rnd.nextInt(num + 1) + 1;

    for (int j = 0; j < n; j++) {
        res.add(rnd.nextDouble());
    }

    return res;
}

The reason for not using any frameworks is that I want to understand the original multithreading.

Thanks you in advance.


Solution

  • Try to create a class that extends Thread or implements Runnable, add the details on the calculate() method to the run() method of the new class.

    Now in the for loop of main function create new threads of type of the new class and start() them. Also you need to synchronize the threads. Reference