gpt4 book ai didi

java - 在不同线程中运行任务

转载 作者:行者123 更新时间:2023-12-01 11:27:53 24 4
gpt4 key购买 nike

如何在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com