如何在M-threads中运行我的任务N次?例如,我有一些任务
public static Runnable createTask () {
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("simple task");
}
};
return runnable;
}
我需要N次运行此任务并将工作分成M个线程。
答案 0 :(得分:1)
你走了。如果你想要运行相同的任务" N"时间,然后创造" N" Callable
相同任务的实例,并将其添加到Callable
List
中,您将传递给invokeAll
方法。
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();
}