如何在M线程中N次运行任务?例如,我有一些任务
public static Runnable createTask () {
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("simple task");
}
};
return runnable;
}
我需要运行此任务N次,并将工作划分为M个线程。
干得好。如果您希望同一任务运行“ N”次,则创建Callable
同一任务的“ N”个实例,并将其添加到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();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句