Skip to content

Instantly share code, notes, and snippets.

@isicju
Created January 23, 2022 21:10
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 isicju/469ef2d1089535c96750bb0416812c2a to your computer and use it in GitHub Desktop.
Save isicju/469ef2d1089535c96750bb0416812c2a to your computer and use it in GitHub Desktop.
Thread Pool Example Java
import java.util.*;
import static java.lang.Thread.currentThread;
public class Main {
static class ThreadPool {
Queue<Runnable> tasks = new LinkedList<>();
public ThreadPool() {
Thread mainWorker = new Thread(() -> {
while (true) {
Runnable newTaskToBeExecuted = tasks.poll();
if (newTaskToBeExecuted != null) newTaskToBeExecuted.run();
}
}, "Main Worker");
mainWorker.start();
}
public void execute(Runnable newTask) {
tasks.add(newTask);
}
}
public static void main(String[] args) {
Runnable firstTask = () -> System.out.println("first task running in thread: " + currentThread().getName());
Runnable secondTask = () -> System.out.println("second task running in thread: " + currentThread().getName());
ThreadPool mySingleThreadPool = new ThreadPool();
mySingleThreadPool.execute(firstTask);
mySingleThreadPool.execute(secondTask);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment