Advertisement
Kostiggig

FixedThreadPool

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