Skip to content

Instantly share code, notes, and snippets.

@mahadevshindhe
Last active November 9, 2021 08:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mahadevshindhe/89517afd1c2562a4e5ebbdc85735af40 to your computer and use it in GitHub Desktop.
Save mahadevshindhe/89517afd1c2562a4e5ebbdc85735af40 to your computer and use it in GitHub Desktop.
Java custom thread pool implementation
public class Main {
public static void main(String[] args) {
ThreadPool pool = new ThreadPool(7);
for (int i = 0; i < 5; i++) {
Task task = new Task(i);
pool.execute(task);
}
}
}
public class Task implements Runnable {
private int num;
public Task(int n) {
num = n;
}
public void run() {
System.out.println("Task " + num + " is running.");
}
}
import java.util.concurrent.LinkedBlockingQueue;
public class ThreadPool {
private final int nThreads;
private final PoolWorker[] threads;
private final LinkedBlockingQueue<Runnable> queue;
public ThreadPool(int nThreads) {
this.nThreads = nThreads;
queue = new LinkedBlockingQueue();
threads = new PoolWorker[nThreads];
for (int i = 0; i < nThreads; i++) {
threads[i] = new PoolWorker();
threads[i].start();
}
}
public void execute(Runnable task) {
synchronized (queue) {
queue.add(task);
queue.notify();
}
}
private class PoolWorker extends Thread {
public void run() {
Runnable task;
while (true) {
synchronized (queue) {
while (queue.isEmpty()) {
try {
queue.wait();
} catch (InterruptedException e) {
System.out.println("An error occurred while queue is waiting: " + e.getMessage());
}
}
task = queue.poll();
}
try {
task.run();
} catch (RuntimeException e) {
System.out.println("Thread pool is interrupted due to an issue: " + e.getMessage());
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment