Java and contract to learn a threadfactory introduction

Source: Internet
Author: User

Threadfactory is a thread factory, as the name implies, is used to create threads, it uses the idea of Factory mode. It is usually used in conjunction with the thread pool, primarily to control some behavior when creating new threads, such as setting the priority of threads, names, and so on. It is an interface and there is only one method in the interface:

/** * * * * * * * * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public Domain, as explained at *http://creativecommons.org/publicdomain/zero/1.0/ */ Packagejava.util.concurrent;/*** An object, creates new threads on demand. Using Thread Factories * Removes hardwiring of calls to {@linkThread#thread (Runnable) New Thread}, * Enabling applications to use special thread subclasses, priorities, etc. * * & Lt;p> * The simplest implementation of this interface is just: * <pre> * class Simplethreadfactory implements THR eadfactory {* Public Thread Newthread (Runnable r) {* Return new Thread (r); *} *} * </pre> * * The {@linkExecutors#defaultthreadfactory} method provides a more * useful simple implementation, that sets the created thread C Ontext * to known values before returning it. * @since1.5 *@authorDoug Lea*/ Public InterfaceThreadfactory {/*** Constructs a new {@codeThread}. Implementations may also initialize * priority, name, daemon status, {@codeThreadgroup}, etc. *     * @paramR A runnable to is executed by new thread instance *@returnconstructed thread, or {@codeNULL} If the request to * Create a thread is rejected*/Thread Newthread (Runnable R);}

The following defines the Newthread method for the MyThreadFactoryTest1 class to implement the Threadfactory interface: When creating a thread, set the name for the thread, with the following code:

 Packageconcurrentmy.threadfactory;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;Importjava.util.concurrent.ThreadFactory;ImportJava.util.concurrent.atomic.AtomicInteger;/*** * (description of type function description) * * <p> * Revision history: <br> * Modification Date Modified by person Revision Content <br> *-------------------------------------------------<br> * March 15, 2016 6:31: User 1.0 Initialization Creation <br> * </p> * *@authorPeng.li *@version1.0 *@sinceJDK1.7*/ Public classMyThreadFactoryTest1ImplementsThreadfactory {Private FinalAtomicinteger count =NewAtomicinteger (0); //private final String nameprefix = "jmsgpool-" + count.incrementandget () + "-" + "Persistencewrite" + "-thread-"; @Override Publicthread Newthread (Runnable r) {thread T=NewThread (R); T.setname ("jmsgpool-" + count.incrementandget () + "-" + "Persistencewrite" + "-thread"); System.out.println ("Create new Thread, thread name:" +t.getname ()); returnT; }    /*** * (TEST) * *@paramargs*/     Public Static voidMain (string[] args) {Executorservice service= Executors.newfixedthreadpool (5,NewMyThreadFactoryTest1 ());  for(inti = 0; I <= 5; i++) {Service.submit (NewRunnable () {@Override Public voidrun () {System.out.println ("Start Execute ...");        }            }); }    }}

Create new Thread, thread Name:jmsgpool-1-persistencewrite-thread
Create new Thread, thread Name:jmsgpool-2-persistencewrite-thread
Start Execute ...
Create new Thread, thread Name:jmsgpool-3-persistencewrite-thread
Start Execute ...
Create new Thread, thread Name:jmsgpool-4-persistencewrite-thread
Start Execute ...
Create new Thread, thread Name:jmsgpool-5-persistencewrite-thread
Start Execute ...
Start Execute ...
Start Execute ...

default threadfactory in JDK

There is a defaultthreadfactory class in the Executors class of the JDK, which implements the Threadfactory, which is the default thread factory class in the JDK, from which the source can see that the thread factory class is set to the name of the newly created thread in the thread pool:

/*** The default thread factory*/    Static classDefaultthreadfactoryImplementsThreadfactory {Private Static FinalAtomicinteger Poolnumber =NewAtomicinteger (1); Private FinalThreadgroup Group; Private FinalAtomicinteger Threadnumber =NewAtomicinteger (1); Private FinalString Nameprefix; Defaultthreadfactory () {SecurityManager s=System.getsecuritymanager (); Group= (s! =NULL) ?S.getthreadgroup (): Thread.CurrentThread (). Getthreadgroup (); Nameprefix= "pool-" +poolnumber.getandincrement ()+ "-thread-"; }         Publicthread Newthread (Runnable r) {thread T=NewThread (Group, R, Nameprefix+threadnumber.getandincrement (),0); if(T.isdaemon ()) T.setdaemon (false); if(T.getpriority ()! =thread.norm_priority) t.setpriority (thread.norm_priority); returnT; }    }

Java and contract to learn a threadfactory introduction

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.