Home > other >  Improve calculation time in parallel mode
Improve calculation time in parallel mode

Time:05-21

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.

CodePudding user response:

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

CodePudding user response:

I will try to answer on a conceptual level:

  • You could spawn a Thread for each task
  • You could spawn n threads that use a (synchronized) Queue<Task> to obtain more work

You will have to synchronize whenever a thread finishes its part.

  • Related