Created
January 23, 2022 21:10
-
-
Save isicju/469ef2d1089535c96750bb0416812c2a to your computer and use it in GitHub Desktop.
Thread Pool Example Java
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.*; | |
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