简体   繁体   English

在不同线程中运行任务

[英]Run tasks in different threads

How can I run my task N-times in M-threads? 如何在M线程中N次运行任务? For example, I have some task 例如,我有一些任务

public static Runnable createTask () {
   Runnable runnable = new Runnable() {
     @Override
     public void run() {               
        System.out.println("simple task");
     }
   };
return runnable;
}

I need to run this task N-times and divide the work into M-threads. 我需要N次运行此任务,并将工作分为M个线程。

Here you go. 干得好。 If you want same task to run "N" time, then create "N" Callable instance of same task and add it in the Callable List which you will pass to invokeAll method. 如果您希望同一任务运行“ N”次,则创建同一任务的“ N”个Callable实例,并将其添加到您将传递给invokeAll方法的“ Callable List中。

      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();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM