Java Executors use custom ThreadFactory

Description

Java Executors use custom ThreadFactory


import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
class MyThreadFactory implements ThreadFactory {
  private int counter;
  private String prefix;
  
  public MyThreadFactory (String prefix) {
    this.prefix=prefix;
    counter=1;/*from ww  w .  ja  va  2s . c  om*/
  }
  
  @Override
  public Thread newThread(Runnable r) {
    MyThread myThread=new MyThread(r,prefix+"-"+counter);
    counter++;
    return myThread;
  }
}
 class MyThread extends Thread {
  
  private Date creationDate=new Date();
  
  private Date startDate;
  
  private Date finishDate;
  
  public MyThread(Runnable target, String name ){
    super(target,name);
  }
  @Override
  public void run() {
    startDate=new Date();
    super.run();
    finishDate=new Date();
    System.out.printf("Thread: %s\n",toString());
  }
  public long getExecutionTime() {
    long ret;
    ret=finishDate.getTime()-startDate.getTime();
    return ret;
  }
  public String toString(){
    StringBuffer buffer=new StringBuffer();
    buffer.append(getName());
    buffer.append(" Creation Date: ");
    buffer.append(creationDate);
    buffer.append(" : Running time: ");
    buffer.append(getExecutionTime());
    buffer.append(" Milliseconds.");
    return buffer.toString();
  }
}
 class MyTask implements Runnable {
  @Override
  public void run() {
    try {
      TimeUnit.SECONDS.sleep(2);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
}

public class Main {
  public static void main(String[] args) throws Exception {
    MyThreadFactory threadFactory=new MyThreadFactory("MyThreadFactory");
    ExecutorService executor=Executors.newCachedThreadPool(threadFactory);
    MyTask task=new MyTask();
    executor.submit(task);
    executor.shutdown();
    executor.awaitTermination(1, TimeUnit.MINUTES);
  }
}



PreviousNext

Related