I am creating a program to calculate values of two arrays in steps of simulation (they are initialized from the beginning, I did not put it here). I would like to do it with threads and ExecutorService. I divided arrays into blocks and I want values of these blocks to be calculated by threads, one block = one thread. These two arrays - X and Y - take values from each other (as you can see in run()), I want X to be calculated first and Y after that, so I made two separate runnables:
public static class CountX implements Runnable {
private int start;
private int end;
private CountDownLatch cdl;
public CountX(int s, int e, CountDownLatch c) {
this.start = s;
this.end = e;
this.cdl = c;
}
public void run() {
for (int i = start + 1; i < end - 1; i++) {
x[i] = x[i] - (y[i-1] - 2 * y[i] + y[i+1]) + y[i];
}
cdl.countDown();
}
}
And same for CountY. I would like to give to it the information where the start and end of value for every block is.
This is, in a short, how my main looks like and this is the main problem of mine:
int NN = 400; //length of X and Y
int threads = 8;
int block_size = (int) NN/threads;
final ExecutorService executor_X = Executors.newFixedThreadPool(threads);
final ExecutorService executor_Y = Executors.newFixedThreadPool(threads);
CountDownLatch cdl = new CountDownLatch(threads);
CountX[] runnables_X = new CountX[threads];
CountY[] runnables_Y = new CountY[threads];
for (int r = 0; r < threads; r++) {
runnables_X[r] = new CountX((r*block_size), ((r+1)*block_size), cdl);
}
for (int r = 0; r < threads; r++) {
runnables_Y[r] = new CountY((r*block_size), ((r+1)*block_size), cdl);
}
int sim_steps = 4000;
for(int m = 0; m < sim_steps; m++) {
for (int e = 0; e < threads; e++) {
executor_X.execute(runnables_X[e]);
}
for (int e = 0; e < threads; e++) {
executor_Y.execute(runnables_Y[e]);
}
}
executor_X.shutdown();
executor_Y.shutdown();
I get wrong values of arrays X and Y from this program, because I also did it without threads.
Is CountDownLatch necessary here? Am I supposed to do for loop of runnables_X[r] = new CountX((r*block_size), ((r+1)*block_size), cdl);
in every m (sim_step) loop? Or maybe I should use ExecutorService in a different way? I tried many options but the results are still wrong.
Thank you in advance!
question from:
https://stackoverflow.com/questions/65937265/java-threading-divided-into-blocks-array-executor-service 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…