Thread Pool in Java

Creating a new Thread for every Job in Java may cause performance and memory-related problems. To overcome these problems we can use Thread Pool in Java. A Thread Pool is a pool/ collection of already created threads.

In Java 1.5v Thread pool framework is introduced to implement thread pool. Thread Pool framework in also known as the Executor framework in Java.

Creating Thread Pool in Java

    ExecutorService threadPool = Executors.newFixedThreadPool(3);

Submit a Job to Thread Pool

We can submit a Runnable job by using submit method

Future<?> submit( @NotNull  Runnable task )

Shutdown Thread Pool

we can shutdown thread pool / ExecutorService by using shutdown method

void shutdown()

Thread Pool Example

package thread;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class Print implements Runnable {
    String name;
    public Print(String name) {
        this.name = name;
    }
    @Override
    public void run() {
        System.out.println(  name + " Job started by thread" + Thread.currentThread().getName());
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {

        }
        System.out.println(name + " Job Completed By Thread" + Thread.currentThread().getName());
    }
}

public class ThreadPoolExample {
    public static void main(String[] args) {
        Print[] jobs = {
                new Print("The Code Data1"),
                new Print("The Code Data2"),
                new Print("The Code Data3"),
                new Print("The Code Data4"),
        };

        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        for(Print job:jobs){
            threadPool.submit(job);
        }
        threadPool.shutdown();
    }
}
package thread;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class Print implements Runnable {
    String name;
    public Print(String name) {
        this.name = name;
    }
    @Override
    public void run() {
        System.out.println(  name + " Job started by thread" + Thread.currentThread().getName());
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {

        }
        System.out.println(name + " Job Completed By Thread" + Thread.currentThread().getName());
    }
}

public class ThreadPoolExample {
    public static void main(String[] args) {
        Print[] jobs = {
                new Print("The Code Data1"),
                new Print("The Code Data2"),
                new Print("The Code Data3"),
                new Print("The Code Data4"),
        };

        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        for(Print job:jobs){
            threadPool.submit(job);
        }
        threadPool.shutdown();
    }
}
Thread Pool Example

In the above example, 3 threads are responsible to execute 4 Runnable jobs.

Similar Java Tutorials

1 thought on “Thread Pool in Java”

Leave a Comment