2013-08-30

Java: Simple multithreading a piece of code

import java.util.*;
import java.util.concurrent.*;

// ...

ExecutorService exec = Executors.newFixedThreadPool(2 * Runtime.getRuntime().availableProcessors());
try {
    for (int i = 0; i < num_of_runs; i++) {
        exec.submit(new Runnable() {
            @Override
            public void run() {
                // do stuff in num_of_runs times through a 2*#CPU threadpool
            }
        });
    }
} finally {
    exec.shutdown();
}

No comments :

Post a Comment