Reputation: 51
How can I run my task N-times in M-threads? For example, I have some task
public static Runnable createTask () {
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("simple task");
}
};
return runnable;
}
I need to run this task N-times and divide the work into M-threads.
Upvotes: 0
Views: 100
Reputation: 14678
Here you go. If you want same task to run "N" time, then create "N" Callable
instance of same task and add it in the Callable
List
which you will pass to invokeAll
method.
try {
List<Callable<Object>> callableList = new ArrayList<Callable<Object>>();
callableList.add(null); /*Add instance of Callable*/
callableList.add(null); /*Add instance of Callable*/
callableList.add(null); /*Add instance of Callable*/
//Specify how many threads you want or need to operate. Read other methods of Executors which return different instances of ExecutorService
final ExecutorService service = Executors.newFixedThreadPool(3);
//This will invoke all your N tasks in specified M threads ...
service.invokeAll(callableList);
} catch (InterruptedException e) {
e.printStackTrace();
}
Upvotes: 1