Advertisement
Kostiggig

ScheduledThreadPool

May 6th, 2023
727
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.09 KB | None | 0 0
  1. package multithreading.thread_pool.types;
  2.  
  3. import java.util.HashSet;
  4. import java.util.Set;
  5. import java.util.concurrent.*;
  6.  
  7. public class ScheduledThreadPoolClient {
  8.  
  9.     private static final int TASKS_COUNT = 10_000;
  10.     private static final Set<String> threadNames = new HashSet<>();
  11.     public static void main(String[] args) throws InterruptedException {
  12.         ScheduledExecutorService service = Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors());
  13.  
  14.         for (int i = 0; i < TASKS_COUNT; i++) {
  15.             int finalI = i;
  16.             Runnable task = () -> {
  17.                 System.out.println("Thread " + Thread.currentThread().getName() + " executes " + finalI + " task");
  18.                 synchronized (threadNames) {
  19.                     threadNames.add(Thread.currentThread().getName());
  20.                 }
  21.             };
  22.             service.schedule(task, 1, TimeUnit.SECONDS);
  23.         }
  24.  
  25.         service.shutdown();
  26.         service.awaitTermination(30, TimeUnit.SECONDS);
  27.         System.out.println("Count of used threads " + threadNames.size());
  28.     }
  29. }
  30.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement