Java ThreadPoolExecutor monitor

Description

Java ThreadPoolExecutor monitor

import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

class Task implements Runnable {
  public Task() {
  }/*from  ww w  .  j a  v a  2  s. c o m*/

  @Override
  public void run() {
    System.out.println("Begin:"+ Thread.currentThread().getName());
    try {
      TimeUnit.MILLISECONDS.sleep(2000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    System.out.println("End:"+ Thread.currentThread().getName());
  }
}

public class Main {
  public static void main(String[] args) throws Exception {
    ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
    for (int i = 0; i < 10; i++) {
      Task task = new Task();
      executor.submit(task);
    }
    for (int i = 0; i < 5; i++) {
      System.out.println("Core Pool Size:"+ executor.getCorePoolSize());
      System.out.println("Pool Size: "+ executor.getPoolSize());
      System.out.println("Active Count: "+ executor.getActiveCount());
      System.out.println("Task Count: "+ executor.getTaskCount());
      System.out.println("Completed Task Count: "+ executor.getCompletedTaskCount());
      System.out.println("Shutdown: "+ executor.isShutdown());
      System.out.println("Terminating: "+ executor.isTerminating());
      System.out.println("Terminated: "+ executor.isTerminated());
      TimeUnit.SECONDS.sleep(1);
    }
    executor.shutdown();
    for (int i = 0; i < 5; i++) {
      System.out.println("Core Pool Size:"+ executor.getCorePoolSize());
      System.out.println("Pool Size: "+ executor.getPoolSize());
      System.out.println("Active Count: "+ executor.getActiveCount());
      System.out.println("Task Count: "+ executor.getTaskCount());
      System.out.println("Completed Task Count: "+ executor.getCompletedTaskCount());
      System.out.println("Shutdown: "+ executor.isShutdown());
      System.out.println("Terminating: "+ executor.isTerminating());
      System.out.println("Terminated: "+ executor.isTerminated());
      TimeUnit.SECONDS.sleep(1);
    }
    executor.awaitTermination(1, TimeUnit.DAYS);
  }
}



PreviousNext

Related