'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 1:[1]
I will try to answer on a conceptual level:
- You could spawn a
Threadfor each task - You could spawn
nthreads that use a (synchronized)Queue<Task>to obtain more work
You will have to synchronize whenever a thread finishes its part.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | roookeee |
