To create a thread using the Java.util.concurrent.ThreadFactory class

Source: Internet
Author: User

The factory design pattern is one of the most commonly used design patterns in Java. It is a creation design pattern that can be used to create objects that are required for one or more classes. With this factory, we can create objects centrally.


The centralized creation approach brings us some benefits, such as:
1. Can easily change the object created by the class or how to create the object;
2. It is easy to restrict the creation of objects, for example: we can only create N objects for Class A;
3. It is easy to generate statistical data about object creation.


In Java, we typically use two ways to create threads: inheriting the thread class and implementing the Runnable interface. Java also provides an interface, both threadfactory interfaces, to create your own thread object factory.


Many classes, for example: Threadpoolexecutor, use constructors to receive threadfactory as arguments. This factory parameter will create a new thread when the program executes. With threadfactory, you can customize how the executor creates the thread, such as defining the appropriate name, 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, and we save the creation information for 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

<span style= "FONT-SIZE:18PX;"   >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_" + C      Ounter);      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 (); }}</span>

In order to use the thread factory above, see the following execution program:

<span style= "FONT-SIZE:18PX;" >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 <=; i++)  {     thread = factory.newthread (Task);     Thread.Start ();  }  System.out.printf ("All Threads is created now\n\n");  System.out.printf ("Give me customthreadfactory stats:\n\n" + factory.getstats ());} </span>

Program execution Results:

<span style= "FONT-SIZE:18PX;" >output:starting the Threads all Threads is created now Give me customthreadfactory stats:created thread 9 with Nam E customthreadfactory-thread_1 on Tue Jan 13:18:04 IST 2015Created Thread Ten with name Customthreadfactory-thread_2 on Tue Jan 13:18:04 ist 2015Created thread One with name customthreadfactory-thread_3 on Tue Jan 13:18:04 ist 2015Create D thread, with name Customthreadfactory-thread_4 on Tue Jan 13:18:04 IST 2015Created thread, with name Customthread Factory-thread_5 on Tue Jan 13:18:04 IST 2015Created Thread + name customthreadfactory-thread_6 on Tue Jan 06 13: 18:04 IST 2015Created thread with name customthreadfactory-thread_7 on Tue Jan 13:18:04 IST 2015Created thread WI Th name customthreadfactory-thread_8 on Tue Jan 13:18:04 IST 2015Created Thread, with name Customthreadfactory-thread _9 on Tue Jan 13:18:04 IST 2015Created thread + name customthreadfactory-thread_10 on Tue Jan 06 13:18:04 IST 2015</span> 

In the above code, thethreadfactory interface has only one method called Newthread () , which 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!!


Original connection: Creating Threads Using java.util.concurrent.ThreadFactory

To create a thread using the Java.util.concurrent.ThreadFactory class

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.