java—如何知道completionservice中有哪些调用引发异常?

jutyujz0  于 2021-06-27  发布在  Java
关注(0)|答案(1)|浏览(304)

我正在并行调用一些方法。如果有方法抛出异常,我想使用传递给方法的值。
请忽略任何语法错误。

public static void main() {
     Executor executor = Executors.newFixedThreadPool(3);
     CompletionService<SomeResult> executorCompletionService = new ExecutorCompletionService<SomeResult>(executor);
     List<Future<Integer>> futures = new ArrayList<>();

     futures.add(executorCompletionService.submit(() -> someMethod(parameterValueForFirstCall)));
     futures.add(executorCompletionService.submit(() -> someMethod(parameterValueForSecondCall)));
     futures.add(executorCompletionService.submit(() -> someMethod(parameterValueForThirdCall)));

     for (int i=0; i<3; i++){

        try {
            executorCompletionService.take().get();       
        } catch(Exception e) {
         System.out.println("exception caught :" + e.getMessage());
         //do something with parameter passed to method that threw exception
     }
 }
bn31dyow

bn31dyow1#

像这样的?

import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class TestThread {

   public static void main(final String[] arguments) throws InterruptedException {
      ExecutorService executor = Executors.newFixedThreadPool(3);
      ArrayList<FutureTask<Integer>> futures =
        new ArrayList<FutureTask<Integer>>();

      // Cast the object to its class type
      ThreadPoolExecutor pool = (ThreadPoolExecutor) executor;

      //Stats before tasks execution
      System.out.println("Largest executions: "
         + pool.getLargestPoolSize());
      System.out.println("Maximum allowed threads: "
         + pool.getMaximumPoolSize());
      System.out.println("Current threads in pool: "
         + pool.getPoolSize());
      System.out.println("Currently executing threads: "
         + pool.getActiveCount());
      System.out.println("Total number of threads(ever scheduled): "
         + pool.getTaskCount());

      for (int i=0; i<8; i++){
        futures.add( new FutureTask<>(new Task(),i*10) );
      }

      System.out.println("Submit all tasks.");
      for (int i=0; i<8; i++){
        executor.submit(futures.get(i));
      }

      System.out.println("Check every second how many tasks unfinished.");

      int done = 1;
      while (done>0) {
        Thread.sleep(1000);
        System.out.println("Next check.");
        done = 0;
        for (int i=0; i<8; i++) {
          System.out.println("Check FT" + i);
          if (!futures.get(i).isDone()) {
            done = 1;
          } else {
            System.out.println("FT " + i + " still running?");
          }
        }
      }

      //Stats after tasks execution
      System.out.println("Core threads: " + pool.getCorePoolSize());
      System.out.println("Largest executions: "
         + pool.getLargestPoolSize());
      System.out.println("Maximum allowed threads: "
         + pool.getMaximumPoolSize());
      System.out.println("Current threads in pool: "
         + pool.getPoolSize());
      System.out.println("Currently executing threads: "
         + pool.getActiveCount());
      System.out.println("Total number of threads(ever scheduled): "
         + pool.getTaskCount());

      System.out.println("Get FT returns.");
      for (int i=0; i<8; i++){
        try {
          System.out.println("FT" + i + " returned " + futures.get(i).get());
        } catch (Exception e) {
          System.out.println("FT" + i + " raised " + e);
        }
      }

      executor.shutdown();
   }

   static class Task implements Runnable {

      public void run() {

         try {
            Long duration = (long) (Math.random() * 5);
            System.out.println("Running Task! Thread Name: " +
               Thread.currentThread().getName());
               TimeUnit.SECONDS.sleep(duration);

            System.out.println("Task Completed! Thread Name: " +
               Thread.currentThread().getName());
         } catch (InterruptedException e) {
            e.printStackTrace();
         }
      }
   }
}

相关问题