Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package multithreading.thread_pool;
- public class Api {
- void makeRequest() throws InterruptedException {
- Thread.sleep(3000); // simulate io blocking
- }
- }
- package multithreading.thread_pool;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.concurrent.ArrayBlockingQueue;
- import java.util.concurrent.BlockingQueue;
- public class MyThreadPool {
- private final BlockingQueue<Runnable> tasks;
- private volatile boolean isStopped = false;
- private final List<Thread> threadsInPoll;
- public MyThreadPool(int countOfThreads, int countOfTasks) {
- tasks = new ArrayBlockingQueue<>(countOfTasks);
- threadsInPoll = new ArrayList<>(countOfThreads);
- for (int i = 0; i < countOfThreads; i++) {
- Thread thread = new Thread(() -> {
- while(true) {
- try {
- getTask().run();
- } catch (InterruptedException e) {
- System.out.println("Interruption... tasks left " + tasks.size());
- break;
- }
- }
- }, "Thread " + i);
- threadsInPoll.add(thread);
- }
- threadsInPoll.forEach(Thread::start);
- }
- public void execute(Runnable runnable) throws InterruptedException {
- if (!isStopped) {
- tasks.put(runnable);
- }
- }
- public void stop() {
- synchronized (this) {
- if (isStopped) return;
- isStopped = true;
- threadsInPoll.forEach(Thread::interrupt);
- }
- }
- private Runnable getTask() throws InterruptedException {
- if (!isStopped) {
- return tasks.take();
- }
- throw new InterruptedException();
- }
- }
- Client:
- package multithreading.thread_pool;
- public class Client {
- private static Api api;
- public static void main(String[] args) throws InterruptedException {
- int countOfThreads = 5;
- int countOfTasks = countOfThreads * 3;
- MyThreadPool threadPool = new MyThreadPool(countOfThreads, countOfTasks);
- api = new Api();
- for (int i = 0; i < 15; i++) {
- int finalI = i;
- threadPool.execute(() -> {
- System.out.println("Thread " + Thread.currentThread().getName() + " makes network request number " + finalI);
- makeRequest();
- System.out.println("Thread " + Thread.currentThread().getName() + " fetched response for the network request number " + finalI);
- });
- }
- Thread.sleep(3500);
- threadPool.stop();
- }
- private static void makeRequest() {
- try {
- api.makeRequest();
- } catch (InterruptedException e) {
- System.out.println("Interruption while making a request has occurred");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement