Home »
Java programming language
Thread Pool in Java, How to Create It
In this article, we are going to learn about Thread pool in java, how we can create Thread Pool in java?
By Preeti Jain Last updated : January 26, 2024
Java Thread Pool
- It is a container of threads or (In other words it is a collection of threads which is having capacity to execute our task).
- We can target (or achieve) thread pool by using ThreadPool framework.
- Thread pool can contain multiple threads. Whenever we perform any tasks then thread will come out from the thread pool and complete that task and again go back to the thread pool.
Without Using Thread Pool
If you don't go with thread pool then...
You need to create repeated thread again and again and memory will be wasted and destroy object each time and performance will get down. If number of request increase/decrease then for that we need to create more number of threads.
Using Thread Pool
If you go with thread pool then...
You don't need to create repeated thread again and again and memory will not be wasted and no need to destroy objects each time and performance will be improved.
If number of request increase/decrease then for that we don't need to create more number of threads.
Example
ThreadPool contains 100 threads and number of request is 200 then 100 request will come out to solve first 100 request then after completing task threads will get free and go back to thread pool then 100 threads will come out to resolve next 100 request.
In thread pool we can discuss three things:
- How to create a ThreadPool?
- How to submit a task to a thread at thread pool?
- How to shut down thread pool?
Creating Thread Pool
Let's see how to create Thread pool,
ExecutorService es = Executors.new FixedThreadPool(int);
int is a number of threads in thread pool
Submitting Task
Let's see how to submit a task to a thread at Thread pool by using submit()?
ExecutorServiceObject (es) => es.submit(Runnable obj);
Shutting Down Thread Pool
Let's see how to shut down a threadPool?
ExecutorServiceObject (es) => es.shutdown();
Implementation
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class ThreadPoolClass implements Runnable {
String s;
ThreadPoolClass(String str) {
s = str;
}
public static void main(String[] args) {
ExecutorService es = Executors.newFixedThreadPool(1);
es.submit(new ThreadPoolClass("First Name: Preeti"));
es.submit(new ThreadPoolClass("Second Name: Jain"));
es.shutdown();
}
public void run() {
System.out.println(Thread.currentThread() + s);
}
}
Output
D:\Java Articles>java ThreadPoolClass
Thread[pool-1-thread-1,5,main]First Name: Preeti
Thread[pool-1-thread-1,5,main]Second Name: Jain