Advertisement
Kostiggig

CachedThreadPool

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