使用ThreadFactory

工厂设计模式

  • 很容易改变的类创建的对象或我们创建这些对象的方式。
  • 很容易用有限的资源限制的创建对象,例如,我们只能有N个对象。
  • 很容易生成统计数据对创建的对象。

例子

各种类,如 ThreadPoolExecutor,使用构造函数接受 ThreadFactory作为参数。这个工厂当执行程序创建一个新的线程使用。使用ThreadFactory您可以自定义线程创建的执行者,他们有适当的线程名称、优先级,甚至他们还可以守护进程。

class Task implements Runnable  
{  
   @Override  
   public void run()  
   {  
      try  
      {  
         TimeUnit.SECONDS.sleep(2);  
      } catch (InterruptedException e)  
      {  
         e.printStackTrace();  
      }  
   }  
}  

public class CustomThreadFactory implements ThreadFactory  
{  
   private int          counter;  
   private String       name;  
   private List<String> stats;  
   
   public CustomThreadFactory(String name)  
   {  
      counter = 1;  
      this.name = name;  
      stats = new ArrayList<String>();  
   }  
   
   @Override  
   public Thread newThread(Runnable runnable)  
   {  
      Thread t = new Thread(runnable, name + "-Thread_" + counter);  
      counter++;  
      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();  
   }  

public static void main(String[] args)  
{  
  CustomThreadFactory factory = new CustomThreadFactory("CustomThreadFactory");  
  Task task = new Task();  
  Thread thread;  
  System.out.printf("Starting the Threads\n\n");  
  for (int i = 1; i <= 10; i++)  
  {  
     thread = factory.newThread(task);  
     thread.start();  
  }  
  System.out.printf("All Threads are created now\n\n");  
  System.out.printf("Give me CustomThreadFactory stats:\n\n" + factory.getStats());  
}  

}  


推荐阅读更多精彩内容