I was wondering if it is possible to spawn each loop iteration
(each iteration
into a thread
by itself) and finally collect the result. consider this example, nothing fancy in it at all. Just a simple for-loop
, but the idea is to extend on it. The body of for loop
does not matter, I just filled up with some code. but basically assume it has some expensive calculation which will take few minutes to complete for each iteration. so I want to do each loop calculation in a separate thread.
public class Threadspawns {
private double[] arr = new double[4];
public void calculations(){
for (int i =2; i < 6; i++){
//expensive calculation
arr[i-2]=Math.pow(i,500);
}
}
public static void main(String[] args){
Threadspawns t = new Threadspawns();
long start = System.currentTimeMillis();
t.calculations();
long end = System.currentTimeMillis();
System.out.println(Arrays.toString(t.arr));
System.out.println("time taken "+ (end-start));
}
}
on the same note,
if it is possible to actually split the recursive calls
into multiple threads and collect them as they return.
Example is that of fibonacci
public static int fibonacci(int n){
if (n==0)
return 0;
if (n==1)
return 1;
return fibonacci(n-2)+fibonacci(n-1);
}
It is possible that it cannot be done for fibonacci recurive method. but any other example of paralleling recursive calls between threads IF POSSIBLE would be nice to know.
P.S: I have basic knowledge of Thread and Runnable
, but wondering if the above is doable
Solution to your first requirement that is moving the expensive calculation into a Callable task. Hope it find it useful: