如何在 M 线程中运行我的任务 N 次?例如,我有一些任务
public static Runnable createTask () {
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("simple task");
}
};
return runnable;
}
我需要运行这个任务N次并将工作划分为M个线程。
最佳答案
给你。如果您希望同一任务运行“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();
}
关于java - 在不同线程中运行任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30666149/