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