2016-07-06 86 views
-1
public class ProcessImpl implements Process { 


    @Override 
    public void process() { 

     List<Callable<Boolean>> tasks = new ArrayList<>(); 
     for (int x = 1; x <= 5; x++) { 
      tasks.add(createTask(x)); 
     } 


     for (int i = 1; i <= 6; i++) { //for each group, there are 6 groups 
      //this is a sequential executor 
      //DefaultThreadExecutor extends AbstractThreadExecutor 
      ExecutorService threadExecutor = new DefaultThreadExecutor(); 
      try { 
       threadExecutor.invokeAll(tasks); 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 


    private Callable<Boolean> createTask(final int i) { 
     Callable<Boolean> task = new Callable<Boolean>() { 
      @Override 
      public Boolean call() throws Exception { 
       System.out.println("Performing task " + i + " on thread - " + Thread.currentThread().getName()); 
       return true; 
      } 
     }; 
     return task; 
    } 

} 

在這段代碼中,threadExecutor.invokeAll(tasks);,任務在Main線程上執行。它打印出這樣的事情:如何讓6個線程按順序運行多個任務

Performing task 1 on thread - main 
Performing task 2 on thread - main 
Performing task 3 on thread - main 
Performing task 4 on thread - main 
Performing task 5 on thread - main 
Performing task 1 on thread - main 

我期待有每組線程,所以6個線程總數和每個線程應該按順序完成5個任務。

如何更改process()以實現此目的?因此,每個線程都在同一時間處理5個任務,每個線程不等待任何其他線程。

結果(這可通過隨機的睡眠,我將介紹不同)

Performing task 1 on thread - group1 
Performing task 1 on thread - group2 
Performing task 2 on thread - group2 
Performing task 1 on thread - group3 
Performing task 2 on thread - group1 
Performing task 3 on thread - group2 
+0

順序表示它們一個接一個地處理,意味着任務2必須等待任務1.也許你在這裏不使用正確的單詞。 –

回答

0

您需要使用

@Override 
    public void process() { 

     List<Callable<Boolean>> tasks = new ArrayList<>(); 
     for (int x = 1; x <= 5; x++) { 
      tasks.add(createTask(x)); 
     } 

    ExecutorService service = Executors.newFixedThreadPool(5 or 6 depending on how much threads you want to run in parallel); 

     for (int i = 1; i <= 6; i++) { //for each group, there are 6 groups 
      //this is a sequential executor 
      //DefaultThreadExecutor extends AbstractThreadExecutor 

      try { 
       service.invokeAll(tasks); 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 

初始化yourExecutor服務。現在,您的所有可調用函數都將與您可用的多個CPU進行排隊。

+0

嗨 - 我想要5個任務(代表1000米的接力賽中的200米)由6個線程運行,可以說是比賽中的球隊。所以每個線程都運行5個任務,這意味着他們完成了事件。 – user2781389

+0

好吧,只需將6個Runtime.getRuntime()。availableProcessors()替換掉,然後就可以了:) –

+0

稍等! 5任務6線程?您如何獲得1個可調用1線程關係。沒有辦法用6個線程執行5個任務。 :)) –