Provide Best Programming Tutorials

Thread pool In Java

Thread pool

A thread pool can be used to execute tasks efficiently. Creating Tasks and Threads, you learned how to define a task class by implementing,java.lang.Runnable and how to create a thread to run a task like this:

Runnable task = new TaskClass(task);
​
new Thread(task).start();

This approach is convenient for a single task execution, but it is not efficient for a large number of tasks because you have to create a thread for each task. Starting a new thread for each task could limit throughput and cause poor performance. Using a thread pool is an ideal way to manage the number of tasks executing concurrently. Java provides the Executor interface for executing tasks in a thread pool and the interfaceExecutorService for managing and controlling tasks. ExecutorService is a subinterface of Executor , as shown in fixture below:

Usage of thread pool

package multithreading.executorPool;
​
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
​
public class ExecutorPoolDemo {
​
    public static void main(String[] args) {
        // Create a fixed thread pool with maximum three threads
        ExecutorService executor = Executors.newFixedThreadPool(3);
        // Submit runnable tasks to the executor
        executor.execute(new PrintChar("a", 10));
        executor.execute(new PrintChar("b", 10));
        executor.execute(new PrintChar("c", 10));
​
        // Shut down the executor
        executor.shutdown();
​
    }
}
​
class PrintChar extends Thread {
    private String charToPrint;
    private Integer loopCount;
​
    public PrintChar(String charToPrint, Integer loopCount) {
        this.charToPrint = charToPrint;
        this.loopCount = loopCount;
    }
​
    @Override
    public void run() {
        for (int i = 0; i < loopCount; i++) {
            System.out.print(charToPrint);
        }
    }
}

output

aaaaaaaaaabbcbbbbbbccccbbccccc

Leave a Reply

Close Menu