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

标签 java multithreading

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

相关文章:

java - Listview onClick更改图像中的Android Imageview无法正常工作

java - 在 Android 应用程序中使用单独的类文件时,请帮助解决此错误

c++ - std::thread 相对于 C++ 中 pthread 的优势

java - 如何解释这个线程转储?

java - 从 Java 内存模型的角度理解为什么在构造函数中启动线程是不安全的

java - Spring - 加载 applicationContext.xml 时出现问题

java - 文件输入流/数据输入流

java - 移动字符串数组中的元素,直到所选字母位于索引 0 处

multithreading - goto out of main 和 print threads 的定义

用于后台加载的 C++ 线程