Last active
November 9, 2021 08:18
-
-
Save mahadevshindhe/89517afd1c2562a4e5ebbdc85735af40 to your computer and use it in GitHub Desktop.
Java custom thread pool implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Task implements Runnable { | |
private int num; | |
public Task(int n) { | |
num = n; | |
} | |
public void run() { | |
System.out.println("Task " + num + " is running."); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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