55import java .util .concurrent .ExecutorService ;
66import java .util .concurrent .Executors ;
77
8+ /**
9+ *
10+ * Thread Pool pattern is where a number of threads are created to perform a number of tasks,
11+ * which are usually organized in a queue. The results from the tasks being executed might
12+ * also be placed in a queue, or the tasks might return no result. Typically, there are many
13+ * more tasks than threads. As soon as a thread completes its task, it will request the next
14+ * task from the queue until all tasks have been completed. The thread can then terminate, or
15+ * sleep until there are new tasks available.
16+ *
17+ * In this example we create a list of tasks presenting work to be done. Each task is then
18+ * wrapped into a Worker object that implements Runnable. We create an ExecutorService with
19+ * fixed number of threads (Thread Pool) and use them to execute the Workers.
20+ *
21+ */
822public class App {
923
1024 public static void main ( String [] args ) {
1125
1226 System .out .println ("Program started" );
1327
28+ // Create a list of tasks to be executed
1429 List <Task > tasks = new ArrayList <>();
1530 tasks .add (new PotatoPeelingTask (3 ));
1631 tasks .add (new PotatoPeelingTask (6 ));
@@ -28,11 +43,20 @@ public static void main( String[] args ) {
2843 tasks .add (new PotatoPeelingTask (4 ));
2944 tasks .add (new PotatoPeelingTask (5 ));
3045
46+ // Creates a thread pool that reuses a fixed number of threads operating off a shared
47+ // unbounded queue. At any point, at most nThreads threads will be active processing
48+ // tasks. If additional tasks are submitted when all threads are active, they will wait
49+ // in the queue until a thread is available.
3150 ExecutorService executor = Executors .newFixedThreadPool (3 );
51+
52+ // Allocate new worker for each task
53+ // The worker is executed when a thread becomes
54+ // available in the thread pool
3255 for (int i =0 ; i <tasks .size (); i ++) {
3356 Runnable worker = new Worker (tasks .get (i ));
3457 executor .execute (worker );
3558 }
59+ // All tasks were executed, now shutdown
3660 executor .shutdown ();
3761 while (!executor .isTerminated ()) {
3862 }
0 commit comments