0% found this document useful (0 votes)
52 views3 pages

Thread Pool

The document describes how to create a thread pool using Executors framework in Java. It creates a WorkerThread class that implements Runnable and takes a string command. A SimpleThreadPool class is used to create a fixed thread pool of 5 threads and submits 10 WorkerThread tasks to the pool. It then shuts down the executor once tasks are completed. A second example shows how to create a ThreadPoolExecutor with a custom RejectedExecutionHandler and MonitorThread to print pool statistics periodically before shutting down the pool.

Uploaded by

Ghanshyam Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views3 pages

Thread Pool

The document describes how to create a thread pool using Executors framework in Java. It creates a WorkerThread class that implements Runnable and takes a string command. A SimpleThreadPool class is used to create a fixed thread pool of 5 threads and submits 10 WorkerThread tasks to the pool. It then shuts down the executor once tasks are completed. A second example shows how to create a ThreadPoolExecutor with a custom RejectedExecutionHandler and MonitorThread to print pool statistics periodically before shutting down the pool.

Uploaded by

Ghanshyam Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 3

public class WorkerThread implements Runnable {

private String command;

public WorkerThread(String s){


this.command=s;
}

@Override
public void run() {
System.out.println(Thread.currentThread().getName()+" Start. Command =
"+command);
processCommand();
System.out.println(Thread.currentThread().getName()+" End.");
}

private void processCommand() {


try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

@Override
public String toString(){
return this.command;
}
}
_______________________________________________

ExecutorService Example
Here is the test program class SimpleThreadPool.java, where we are creating fixed
thread pool from Executors framework.

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SimpleThreadPool {

public static void main(String[] args) {


ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
Runnable worker = new WorkerThread("" + i);
executor.execute(worker);
}
executor.shutdown();
while (!executor.isTerminated()) {
}
System.out.println("Finished all threads");
}
}
___________________________________________________________________________________
_____________________

Example === 2 : ThreadPoolExecutor Example

import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

public class RejectedExecutionHandlerImpl implements RejectedExecutionHandler {

@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
System.out.println(r.toString() + " is rejected");
}

import java.util.concurrent.ThreadPoolExecutor;

public class MyMonitorThread implements Runnable


{
private ThreadPoolExecutor executor;
private int seconds;
private boolean run=true;

public MyMonitorThread(ThreadPoolExecutor executor, int delay)


{
this.executor = executor;
this.seconds=delay;
}
public void shutdown(){
this.run=false;
}
@Override
public void run()
{
while(run){
System.out.println(
String.format("[monitor] [%d/%d] Active: %d, Completed: %d,
Task: %d, isShutdown: %s, isTerminated: %s",
this.executor.getPoolSize(),
this.executor.getCorePoolSize(),
this.executor.getActiveCount(),
this.executor.getCompletedTaskCount(),
this.executor.getTaskCount(),
this.executor.isShutdown(),
this.executor.isTerminated()));
try {
Thread.sleep(seconds*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}
}

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class WorkerPool {


public static void main(String args[]) throws InterruptedException{
//RejectedExecutionHandler implementation
RejectedExecutionHandlerImpl rejectionHandler = new
RejectedExecutionHandlerImpl();
//Get the ThreadFactory implementation to use
ThreadFactory threadFactory = Executors.defaultThreadFactory();
//creating the ThreadPoolExecutor
ThreadPoolExecutor executorPool = new ThreadPoolExecutor(2, 4, 10,
TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(2), threadFactory,
rejectionHandler);
//start the monitoring thread
MyMonitorThread monitor = new MyMonitorThread(executorPool, 3);
Thread monitorThread = new Thread(monitor);
monitorThread.start();
//submit work to the thread pool
for(int i=0; i<10; i++){
executorPool.execute(new WorkerThread("cmd"+i));
}

Thread.sleep(30000);
//shut down the pool
executorPool.shutdown();
//shut down the monitor thread
Thread.sleep(5000);
monitor.shutdown();

}
}

You might also like