![](/img/trans.png)
[英]executor service in java for multi threading, ignore the details of threading?
[英]Java: threading divided into blocks array - executor service
我正在创建一个程序来在模拟步骤中计算两个 arrays 的值(它们从头开始初始化,我没有放在这里)。 我想用线程和 ExecutorService 来做。 我将 arrays 分成块,我希望这些块的值由线程计算,一个块 = 一个线程。 这两个 arrays - X 和 Y - 相互取值(如您在 run() 中所见),我希望先计算 X,然后计算 Y,所以我制作了两个单独的可运行文件:
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();
}
}
CountY 也是如此。 我想向它提供每个块的值的开始和结束位置的信息。
简而言之,这是我的主要外观,这是我的主要问题:
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();
我从这个程序中得到了错误的 arrays X 和 Y 值,因为我也没有线程。 这里需要 CountDownLatch 吗? 我应该为runnables_X[r] = new CountX((r*block_size), ((r+1)*block_size), cdl);
循环做吗? 在每个 m (sim_step) 循环中? 或者也许我应该以不同的方式使用 ExecutorService? 我尝试了很多选项,但结果仍然是错误的。 先感谢您!
您的方法是我可能不会为这项任务采取的方法。
您可以使用引用和 Runnables,但在您的情况下, Callable可能是更好的选择。 使用 Callable,您只需给它数组并让它计算部分值,如果可能的话并等待Futures
。 对我来说,虽然不清楚你真正想要计算什么,所以我在这里盲目猜测。
您不需要CountDownLatch
也不需要两个ExecutorServices
- 一个 EXS 就足够了。
如果您真的想为此使用Runnable
,您应该使用并发列表、原子变量、 volatile
或锁来实现某种同步。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.