Java executor framework for running multi-threaded applications concurrently, sequentially, and with a strategy design pattern to switch between sequential and concurrent execution. 1. Running concurrently
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
package com.writtentest13; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * Tasks are executed concurrently in a thread pool */ public class ThreadExecutorMainCon { private ExecutorService concurrentThreadExecutor; public static void main(String[] args) { ThreadExecutorMainCon main = new ThreadExecutorMainCon(); // concurrent executor main.concurrentThreadExecutor = Executors.newCachedThreadPool();// or // newFixedThreadPool(3) List<Callable<Boolean>> tasks = new ArrayList<Callable<Boolean>>(); // create dummy tasks for (int i = 1; i <= 5; i++) { tasks.add(main.createTask(i)); } // submit the tasks to the concurrentThreadExecutor try { main.concurrentThreadExecutor.invokeAll(tasks); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Completed ........."); } 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; } } |
The output will be
|
1 2 3 4 5 6 7 |
Performing task 1 on thread - pool-1-thread-1 Performing task 5 on thread - pool-1-thread-4 Performing task 4 on thread - pool-1-thread-1 Performing task 3 on thread - pool-1-thread-3 Performing task 2 on thread - pool-1-thread-2 Completed ......... |
You can see more than 1 thread process 5 tasks concurrently. … Read more ›...