Skip to content

Instantly share code, notes, and snippets.

@pancanin
Created January 31, 2020 22:48
Show Gist options
  • Save pancanin/ed8b955086ca5cfa15a61b9980900f30 to your computer and use it in GitHub Desktop.
Save pancanin/ed8b955086ca5cfa15a61b9980900f30 to your computer and use it in GitHub Desktop.
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class ThreadPool implements IThreadPool {
private List<PoolThread> threads;
private BlockingQueue<ITask> tasks;
private boolean isStopped = false;
public ThreadPool(int numberOfThreads, int maxNumberOfTasks) {
threads = new ArrayList<>();
tasks = new ArrayBlockingQueue<>(maxNumberOfTasks);
this.fillThreads(numberOfThreads);
this.start();
}
@Override
public synchronized void schedule(ITask task) {
if (this.isStopped) {
throw new IllegalArgumentException("Cannot accept any more tasks!");
}
try {
this.tasks.put(task);
} catch (InterruptedException e) {
// well someone interrupted the process..
}
}
@Override
public synchronized void stop() {
this.isStopped = true;
for (PoolThread thread : this.threads) {
thread.stopThread();
}
}
private void start() {
for (Thread thread : this.threads) {
thread.start();
}
}
private void fillThreads(int numberOfThreads) {
for (int i = 0; i < numberOfThreads; i++) {
this.threads.add(new PoolThread(this.tasks));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment