Use the java. util. concurrent. ThreadFactory class to create a thread

Source: Internet
Author: User

Use the java. util. concurrent. ThreadFactory class to create a thread

The factory design pattern is one of the most common design patterns in Java. It is a creation-type design pattern that can be used to create the objects required by one or more classes. With this factory, we can create objects in a centralized manner.

 

The centralized creation method brings us some benefits, such:
1. It is easy to change the object created by the class or the method of creating the object;
2. It is easy to restrict the creation of objects. For example, we can only create N objects for Class;
3. It is easy to generate statistics on Object creation.

 

In Java, we usually use two methods to create a Thread: Inherit the Thread class and implement the Runnable interface. Java also provides an interface, ThreadFactory interface, used to create your own thread object factory.

 

Many classes, such as ThreadPoolExecutor, use constructors to receive ThreadFactory as parameters. This factory parameter will create a new thread during program execution. With ThreadFactory, you can customize how the execution program creates a thread, such as defining a proper name and priority for the thread, or you can even set it as a daemon thread.

 

ThreadFactory example

In this example, we will learn how to create a thread object with a personalized name by implementing a ThreadFactory interface. At the same time, we save the creation Information of the thread object.

 

Task. java

 

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


 

CustomThreadFactory. java

 

 

public class CustomThreadFactory implements ThreadFactory{   private int          counter;   private String       name;   private List
 
   stats;    public CustomThreadFactory(String name)   {      counter = 1;      this.name = name;      stats = new ArrayList
  
   ();   }    @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 , t.getId(), t.getName(), new Date()));      return t;   }    public String getStats()   {      StringBuffer buffer = new StringBuffer();      Iterator
   
     it = stats.iterator();      while (it.hasNext())      {         buffer.append(it.next());      }      return buffer.toString();   }}
   
  
 

To use the preceding thread factory, see the following execution program:

 

 

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

Program Execution result:

 

 

Output : Starting the Threads All Threads are created now Give me CustomThreadFactory stats: Created thread 9 with name CustomThreadFactory-Thread_1 on Tue Jan 06 13:18:04 IST 2015Created thread 10 with name CustomThreadFactory-Thread_2 on Tue Jan 06 13:18:04 IST 2015Created thread 11 with name CustomThreadFactory-Thread_3 on Tue Jan 06 13:18:04 IST 2015Created thread 12 with name CustomThreadFactory-Thread_4 on Tue Jan 06 13:18:04 IST 2015Created thread 13 with name CustomThreadFactory-Thread_5 on Tue Jan 06 13:18:04 IST 2015Created thread 14 with name CustomThreadFactory-Thread_6 on Tue Jan 06 13:18:04 IST 2015Created thread 15 with name CustomThreadFactory-Thread_7 on Tue Jan 06 13:18:04 IST 2015Created thread 16 with name CustomThreadFactory-Thread_8 on Tue Jan 06 13:18:04 IST 2015Created thread 17 with name CustomThreadFactory-Thread_9 on Tue Jan 06 13:18:04 IST 2015Created thread 18 with name CustomThreadFactory-Thread_10 on Tue Jan 06 13:18:04 IST 2015

In the code above, the ThreadFactory interface has only one method called newThread (). It receives a Runnable object as a parameter and returns a Thread object. When you implement the ThreadFactory interface, you must override this method.

 

Happy Learning !!

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.