Java ThreadFactory implement to generate custom threads

Description

Java ThreadFactory implement to generate custom threads


import java.util.Date;
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;/*  www. j a  v a  2  s. c  o m*/
  }

  @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();
  }

  public long getExecutionTime() {
    return finishDate.getTime() - startDate.getTime();
  }

  @Override
  public String toString() {
    StringBuilder buffer = new StringBuilder();
    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 myFactory = new MyThreadFactory("MyThreadFactory");
    MyTask task = new MyTask();
    Thread thread = myFactory.newThread(task);

    thread.start();
    thread.join();
    System.out.printf("%s\n", thread);
  }
}



PreviousNext

Related