【问题标题】:Executors are not running all the threads.执行程序没有运行所有线程。
【发布时间】:2013-12-06 04:51:02
【问题描述】:

我是 Java 新手,我正在尝试这个。我有方法,我希望并行运行该方法。我希望应该有 10 个线程调用该方法并获得它们的结果。

我为此使用CallableExecutors。我将线程池创建为:

 ExecutorService executor = Executors.newFixedThreadPool(10);

当我这样做时:

 executor.invokeAll(taskList);

在 10 个线程中,只有 1 个线程被从投票中取出。我只打印了这个:

The current thread is pool-1-thread-1

但我希望应该有 10 个类似的 println 语句。

这里是完整的代码:

import java.util.concurrent.Callable;
import java.util.List;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.Future;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutorCompletionService;

public class Parallel
{
    public static void main(String args[])
    {
        Learning l = new Learning();
        l.message = "1st Object";
        l.testThread();
    }
}

//this class deals with threads
class Learning
{

    public String message;

    public void setMessage(String message)
    {
        this.message = message;
    }

    //contains the code where
    public void testThread()
    {

       //create a callable for each method
       Callable<String> callable1 = new Callable<String>()
       {
          @Override
          public String call() throws Exception
          {
             System.out.println("The current thread is " + Thread.currentThread().getName());
             return method1();
             // return null;
          }
       };


       //add to a list
       List<Callable<String>> taskList = new ArrayList<Callable<String>>();
       taskList.add(callable1);

       //create a pool executor with 10 threads
       ExecutorService executor = Executors.newFixedThreadPool(10);


       try
       {
         List<Future<String>> futureList = executor.invokeAll(taskList);

       }
       catch (InterruptedException ie)
       {
       }
    }

    //put your code here!
    private String method1()
    {
        return Thread.currentThread().getName();
    }
}

我在这里遗漏了什么吗?

【问题讨论】:

  • 我希望同一个 callable 应该运行 10 次。那是来自线程池。

标签: java multithreading executorservice


【解决方案1】:

您的 ExecutorService 可以运行 10 个线程。但是你只提交了一个线程。将 testThread 方法更改为这样。

// contains the code where
public void testThread() {
    // add to a list
    List<Callable<String>> taskList = new ArrayList<Callable<String>>();
    Callable<String> callable1=null;
    for (int i = 0; i < 10; i++) {
        // create a callable for each method
        callable1 = new Callable<String>() {
            @Override
            public String call() throws Exception {
                System.out.println("The current thread is " + Thread.currentThread().getName());
                return method1();
                // return null;
            }
        };
        taskList.add(callable1);
    }

    // create a pool executor with 10 threads
    ExecutorService executor = Executors.newFixedThreadPool(10);

    try {
        List<Future<String>> futureList = executor.invokeAll(taskList);

    } catch (InterruptedException ie) {
    }
}

【讨论】:

    【解决方案2】:

    如有疑问,请查看 javadoc。如果您阅读 invokeAll 方法,您会发现以下内容

    执行给定的任务,返回一个 Futures 列表,在所有完成后保存它们的状态和结果。

    因此,如果您提供一项任务,它将完成一项任务,如果您希望它完成 10 项任务,则需要提供 10 项任务。此外,当没有更多要提交的任务时,您可以调用

    executor.shutDown()
    

    此方法会在确保所有提交的任务都完成后关闭服务。

    【讨论】:

      【解决方案3】:

      taskList 中只有一个 callable。将更多callables 添加到列表中并在method1() 中休眠一段时间,以便池中的所有10 个线程都忙。

      import java.util.concurrent.Callable;
      import java.util.List;
      import java.util.ArrayList;
      import java.util.concurrent.ExecutorService;
      import java.util.concurrent.Executors;
      import java.util.concurrent.TimeUnit;
      import java.util.concurrent.TimeoutException;
      import java.util.concurrent.Future;
      import java.util.concurrent.ExecutionException;
      import java.util.concurrent.CompletionService;
      import java.util.concurrent.ExecutorCompletionService;
      
      public class Parallel
      {
          public static void main(String args[])
          {
              Learning l = new Learning();
              l.message = "1st Object";
              l.testThread();
          }
      }
      
      //this class deals with threads
      class Learning
      {
      
          public String message;
      
          public void setMessage(String message)
          {
              this.message = message;
          }
      
          //contains the code where
          public void testThread()
          {
      
             //create a callable for each method
             Callable<String> callable1[] = new Callable[10];
      
             for(int i=0;i<10;++i){
             callable1[i] =  new Callable<String>(){
                @Override
                public String call() throws Exception
                {
                   System.out.println("The current thread is " + Thread.currentThread().getName());
                   return method1();
                   // return null;
                }
             };
         }
      
      
         //add to a list
         List<Callable<String>> taskList = new ArrayList<Callable<String>>();
      
         for(int i=0;i<10;++i){
             taskList.add(callable1[i]);
         }
      
         //create a pool executor with 10 threads
         ExecutorService executor = Executors.newFixedThreadPool(10);
      
      
         try
         {
           List<Future<String>> futureList = executor.invokeAll(taskList);
           executor.shutdown();
      
         }
         catch (InterruptedException ie)
         {
         }
      }
      
      //put your code here!
      private String method1()
      {
          return Thread.currentThread().getName();
      }
      }
      

      【讨论】:

        【解决方案4】:

        问题在于执行程序调用了可调用对象或可运行对象。在您的任务列表(列表)中,您仅添加了 1 个可调用类型实例并将此任务列表提交给执行程序。所以执行者只有一项工作要做。将您的更多可调用对象添加到任务列表中,然后提交给执行者。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-03-25
          • 2013-03-31
          • 1970-01-01
          • 1970-01-01
          • 2020-01-26
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多