Java执行程序在执行期间无法添加新任务

时间:2018-05-17 21:51:17

标签: java multithreading

尝试使用执行程序并行运行某些任务。我的任务的特殊之处在于,其中一个执行程序线程可能在执行期间添加新任务(如以下代码段所示)。

以下代码段并不能满足我的需求。如果有人给我一些想法,我将不胜感激。

 public void testThread2() throws Exception {
      Table obj = new Table();//only one object
      ExecutorService taskExecutor = Executors.newFixedThreadPool(3);
      Random rand = new Random();
      final ArrayList<Integer> tasks = new ArrayList<>();
      tasks.add(1);
      tasks.add(2);
      tasks.add(3);
      tasks.add(4);
      for (Integer t: tasks) {
         taskExecutor.execute(() -> {
            for (int j = 0; j< 5; j++) {
               System.out.println(j * 100 + t);
               try {
                  Thread.sleep(rand.nextInt(300));
               } catch (Exception e) {
                  e.printStackTrace();
               }
            }
            if (t == 2) {
               tasks.add(5);
            }
         });
      }
      Thread.sleep(2000);
      taskExecutor.shutdown();
   }

1 个答案:

答案 0 :(得分:2)

提取应在额外方法中运行的代码,并通过调用tasks.add(5);替换taskExecutor.execute()

 public void testThread2() throws Exception {
    Table obj = new Table();//only one object
    ExecutorService taskExecutor = Executors.newFixedThreadPool(3);
    Random rand = new Random();
    final ArrayList<Integer> tasks = new ArrayList<>();
    tasks.add(1);
    tasks.add(2);
    tasks.add(3);
    tasks.add(4);
    for (Integer t: tasks) {
        taskExecutor.execute(() -> testThread2Runner(t, taskExecutor));
    }
    Thread.sleep(2000);
    taskExecutor.shutdown();
}

public static void testThread2Runner(int t, ExecutorService taskExecutor) {
    for (int j = 0; j< 5; j++) {
        System.out.println(j * 100 + t);
        try {
            Thread.sleep(rand.nextInt(300));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    if (t == 2) {
        taskExecutor.execute(() -> testThread2Runner(5, taskExecutor));
    }
}