In this tutorial, we will learn ThreadPool Example. Lets say, Application needs to send 1000 of email as part of nightly job. In this case,

Thread

  • Thread is a Simple Task which is Implemented Runnable Interface or extended Thread class which triggers to send email
  • Thread does unit of work

ThreadPool:

  • A pool of threads is called Thread pool to execute multiple tasks in parallel

Thread Pool With Executors Framework

This example uses the Executors factory class to create a fixed thread pool with 5 threads.

The execute() method is then used to submit tasks to the thread pool, in this case instances of the SendEmailTask class that implement the Runnable interface. Once all tasks have been submitted, the thread pool is shut down using the shutdown() method.

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class ThreadPoolExample {
    public static void main(String[] args) {
        // Create a fixed thread pool with 5 threads
        Executor executor = Executors.newFixedThreadPool(10);

        // Submit multiple tasks to the thread pool
        for (int i = 0; i < 10; i++) {
            Runnable task = new SendEmailTask("EmailTask " + i);
            executor.execute(task);
        }

        // Shut down the thread pool
        ((ExecutorService) executor).shutdown();
    }
}

class SendEmailTask implements Runnable {
    private String name;

    public Task(String name) {
        this.name = name;
    }

    public void run() {
        try {
            EmailUtil.sendEmail();
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(name + " complete");
    }
}

In the above example, Executors.newFixedThread pool creates threads and on submit, SendEmailTask will be executed.

Thanks for Reading.