I have 2 sets of tasks. I create two ThreadPoolExecutor, given them 2 lists of tasks and calling invokeAll methods in both. I see that after all tasks of first ThreadPoolExecutor are complete tasks of second ThreadPoolExecutor are starting. Is there a way to initiate them in parallel?
public class Test3 {
public static void main(String[] args) throws Exception {
String[] works1 = {"work1", "work2", "work3", "work4", "work5"};
String[] works2 = {"work6", "work7", "work8", "work9", "work10", "work11"};
List<String> workList1 = Arrays.asList(works1);
List<String> workList2 = Arrays.asList(works2);
List<Callable<Object>> workerList1 = new ArrayList<Callable<Object>>();
List<Callable<Object>> workerList2 = new ArrayList<Callable<Object>>();
ThreadPoolExecutor executorService1 = (ThreadPoolExecutor) Executors.newFixedThreadPool(3);
ThreadPoolExecutor executorService2 = (ThreadPoolExecutor) Executors.newFixedThreadPool(3);
for(int i=0; i<workList1.size(); i++) {
Runnable worker = new TWorker(workList1.get(i));
Callable<Object> callableWorker = Executors.callable(worker);
workerList1.add(callableWorker);
}
for(int i=0; i<workList2.size(); i++) {
Runnable worker = new TWorker(workList2.get(i));
Callable<Object> callableWorker = Executors.callable(worker);
workerList2.add(callableWorker);
}
System.out.println("Invoke all TP1");
executorService1.invokeAll(workerList1);
System.out.println("Invoke all TP2");
executorService2.invokeAll(workerList2);
executorService1.shutdown();
while(!executorService1.isTerminated()) {}
executorService2.shutdown();
while(!executorService2.isTerminated()) {}
}
}
class TWorker implements Runnable {
private String work;
public TWorker(String work) {
this.work = work;
}
@Override
public void run() {
System.out.println("Thread : "+Thread.currentThread().getName() +" | work : "+work+" | execution start");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread : "+Thread.currentThread().getName() +" | work : "+work+" | execution end");
}
}