Java Executors create a thread executor

Description

Java Executors create a thread executor


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

public class Main {
  public static void main(String[] args) {
    Server server = new Server();
    for (int i = 0; i < 100; i++) {
      Task task = new Task("Task " + i);
      server.executeTask(task);/*  www  .j  av  a 2s.c om*/
    }
    server.endServer();
  }
}


class Server {
  private ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
  public Server() {
  }

  public void executeTask(Task task) {
    System.out.println("A new task has arrived\n");
    executor.execute(task);
    System.out.println("Pool Size: "+ executor.getPoolSize());
    System.out.println("Active Count:"+ executor.getActiveCount());
    System.out.println("Completed Tasks:"+ executor.getCompletedTaskCount());
  }

  public void endServer() {
    executor.shutdown();
  }

}

class Task implements Runnable {

  private Date initDate;

  private String name;

  public Task(String name) {
    initDate = new Date();
    this.name = name;
  }

  @Override
  public void run() {
    System.out.println(Thread.currentThread().getName()+" "+ name+" "+  initDate);
    System.out.println(Thread.currentThread().getName()+" "+  name+" "+  new Date());

    try {
      Long duration = (long) (Math.random() * 10);
      System.out.println(Thread.currentThread().getName()+" "+  name+" "+ duration);
      TimeUnit.SECONDS.sleep(duration);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    System.out.println(Thread.currentThread().getName()+" "+  name+" "+  new Date());
  }

}



PreviousNext

Related