Thread pools

  • Eclipse: Oxygen
  • Java: 1.8

This tutorial is about a thread pool that is a software design pattern for achieving concurrency of execution in a computer program. Often, also called a replicated workers or worker-crew model, a thread pool maintains several threads waiting for tasks to be allocated for concurrent execution by the supervising program.

In the following program, we have SomeThread class which extend Thread. Inside the App class, we are creating fixed thread pool from Executors framework. Then we pass the object of thread type for executing threads.  And shut down the Executor pool.  shutdown() method help us to finish execution of all the submitted tasks and terminate the thread pool.

As we see the application is executing only two threads simultaneously when a thread in the pool becomes idle.

Output

Starting thread: Thread 1

Starting thread: Thread 2

Thread ended: Thread 1

Starting thread: Thread 3

Thread ended: Thread 2

Starting thread: Thread 4

Thread ended: Thread 3

Starting thread: Thread 5

Thread ended: Thread 4

Starting thread: Thread 6

Thread ended: Thread 5

Starting thread: Thread 7

Thread ended: Thread 6

Starting thread: Thread 8

Thread ended: Thread 7

Starting thread: Thread 9

Thread ended: Thread 8

Starting thread: Thread 10

Thread ended: Thread 9

Starting thread: Thread 11

Thread ended: Thread 10

Starting thread: Thread 12

Thread ended: Thread 11

Starting thread: Thread 13

Thread ended: Thread 12

Starting thread: Thread 14

Thread ended: Thread 13

Starting thread: Thread 15

Thread ended: Thread 14

Starting thread: Thread 16

Thread ended: Thread 15

Thread ended: Thread 16

Contributed by: Poonam Tomar


Full stack Java Developer

   Buy me a coffee!

 

PayTM QR (INDIA)

Download file

Leave a Reply

avatar
  Subscribe  
Notify of
Close Menu