Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@jiunbae
Last active November 28, 2017 09:16
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 jiunbae/1d3c3ef9bed1eecf49273003d6c07b4b to your computer and use it in GitHub Desktop.
Save jiunbae/1d3c3ef9bed1eecf49273003d6c07b4b to your computer and use it in GitHub Desktop.
Simple thread pool
package concurrent;
import java.util.Arrays;
import java.util.concurrent.LinkedBlockingQueue;
public class Pool {
private boolean terminate;
private final Worker[] workers;
private final LinkedBlockingQueue<Runnable> queue;
public Pool(int nThreads) {
workers = new Worker[nThreads];
queue = new LinkedBlockingQueue<>();
terminate = false;
for (int i = 0; i < nThreads; ++i) {
workers[i] = new Worker();
workers[i].start();
}
}
public void push(Runnable task) {
synchronized (queue) {
queue.add(task);
queue.notify();
}
}
public void join() {
terminate = true;
for (Worker worker : workers)
try {
worker.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public final int size() {
return queue.size();
}
public final boolean isEmpty() {
return queue.isEmpty();
}
private class Worker extends Thread {
public void run() {
Runnable task;
while (true) {
synchronized (queue) {
while (queue.isEmpty()) {
try {
if (queue.isEmpty() && terminate)
return;
queue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
task = queue.poll();
}
try {
task.run();
} catch (RuntimeException e) {
e.printStackTrace();
}
}
}
}
}
@jiunbae
Copy link
Author

jiunbae commented Nov 28, 2017

Update join method to terminate after join all workers

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment