How to parallelize nested loops in java 7 (android) -


i have following code snippet

 string result;         (int s1 = 0; s1 < 10; s1++)             (int s2 = 0; s2 < 100; s2++)                 (int s3 = 0; s3 < 10; s3++)                     (int s4 = 0; s4 < 100; s4++)                     {                         result = dosomething(s1, s2, s3, s4);                         if (result != null)                             addresult(result); //adds results arraylist of strings                     } 

how can parallelize code make faster? i've seen similar posts here parallelizing single loops want evenly parallelize whole thing make run decently on android device.

you use asynctask parallelize each of s1 executions, e.g.:

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<>();             (int s2 = 0; s2 < 100; s2++)             {                 (int s3 = 0; s3 < 10; s3++)                 {                     (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 assumes order of addresult calls not matter, , of course dosomething calls not interfere each other modifying shared state.

if order of addresult calls matter, solve creating array of results, waiting until finish (by creating counter, , waiting until 10 tasks complete, , processing array of results afterwards, in order.


Comments

Popular posts from this blog

html - Styling progress bar with inline style -

java - Oracle Sql developer error: could not install some modules -

How to use autoclose brackets in Jupyter notebook? -