[英]How to parallelize nested loops in java 7 (android)
I have the following code snippet我有以下代码片段
String result;
for (int s1 = 0; s1 < 10; s1++)
for (int s2 = 0; s2 < 100; s2++)
for (int s3 = 0; s3 < 10; s3++)
for (int s4 = 0; s4 < 100; s4++)
{
result = doSomething(s1, s2, s3, s4);
if (result != null)
addResult(result); //adds results to an ArrayList of strings
}
How can I parallelize this code to make it faster?如何并行化此代码以使其更快? I've seen similar posts here parallelizing a single loops but I want to evenly parallelize this whole thing to make it run decently on an android device.
我在这里看到了类似的帖子并行化单个循环,但我想均匀地并行化整个事情,使其在 android 设备上正常运行。
You could use an AsyncTask
to parallelize each of the s1
executions, eg:您可以使用
AsyncTask
来并行化每个s1
执行,例如:
for (int s1 = 0; s1 < 10; s1++)
{
new AsyncTask<Integer, Object, ArrayList<String>>()
{
@Override
protected ArrayList<String> doInBackground(Integer... params)
{
ArrayList<String> results = new ArrayList<>();
for (int s2 = 0; s2 < 100; s2++)
{
for (int s3 = 0; s3 < 10; s3++)
{
for (int s4 = 0; s4 < 100; s4++)
{
results.add(doSomething(params[0], s2, s3, s4));
}
}
}
return results;
}
@Override
protected void onPostExecute(ArrayList<String> results)
{
for(String result : results) {
if (result != null)
addResult(result);
}
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, s1);
};
Note that this assumes that the order of addResult
calls do not matter, and of course that doSomething
calls do not interfere with each other by modifying some shared state.请注意,这假设
addResult
调用的顺序无关紧要,当然doSomething
调用不会通过修改某些共享状态而相互干扰。
If the order of addResult
calls do matter, you could solve this by creating an array of all the results, waiting until they all finish (by creating a counter, and waiting until all 10 tasks complete, and then processing the array of results afterwards, in order.如果
addResult
调用的顺序很重要,您可以通过创建所有结果的数组来解决这个问题,等待它们全部完成(通过创建一个计数器,并等待所有 10 个任务完成,然后处理结果数组,为了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.