Java ThreadFactory create threads through a factory

Introduction

Java ThreadFactory interface implements a Thread object factory.

The following code shows how to implement a ThreadFactory interface to create Thread objects with a customized name.

The ThreadFactory interface has only one method called newThread.

It receives a Runnable object as a parameter and returns a Thread object.

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

public class Main {
  public static void main(String[] args) {
    MyThreadFactory factory = new MyThreadFactory("MyThreadFactory");
    Task task = new Task();
    // Creates and starts ten Thread objects
    System.out.printf("Starting the Threads\n");
    for (int i = 0; i < 10; i++) {
      Thread thread = factory.newThread(task);
      thread.start();/*from w w  w .  j  a  v a2s .c om*/
    }
    // Prints the statistics of the ThreadFactory to the console
    System.out.printf("Factory stats:\n");
    System.out.printf("%s\n", factory.getStats());
  }
}

class MyThreadFactory implements ThreadFactory {
  private int counter = 0;
  private String name;
  private List<String> stats = new ArrayList<String>();

  public MyThreadFactory(String name) {
    this.name = name;    
  }
  @Override
  public Thread newThread(Runnable r) {
    // Create the new Thread object
    Thread t = new Thread(r, name + "-Thread_" + counter);
    counter++;
    // Actualize the statistics of the factory
    stats.add(String.format("Created thread %d with name %s on %s\n", t.getId(), t.getName(), new Date()));
    return t;
  }

  public String getStats() {
    StringBuffer buffer = new StringBuffer();
    Iterator<String> it = stats.iterator();

    while (it.hasNext()) {
      buffer.append(it.next());
    }
    
    return buffer.toString();
  }
}
class Task implements Runnable {
  @Override
  public void run() {
    try {
      TimeUnit.SECONDS.sleep(1);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
}



PreviousNext

Related