Create the object for the new thread as needed. Using a thread factory eliminates the need to manually write calls to the new thread, allowing applications to use special line Cheng Zi classes, attributes, and so on. Description of the JDK:
An object, the creates new threads on demand. Using thread factories removes hardwiring new Thread of calls to, enabling applications to use special thread subclasses, priori Ties, etc.
The simplest implementation of this interface is just:
class Implements threadfactory { public Thread newthread (Runnable r) { returnNew Thread (R); } }
TheExecutors.defaultThreadFactoryMethod provides a more useful simple implementation, which sets the created thread context to known values before returning It.
/*** The default thread factory*/ Static classDefaultthreadfactoryImplementsThreadfactory {Static FinalAtomicinteger Poolnumber =NewAtomicinteger (1); FinalThreadgroup Group; FinalAtomicinteger Threadnumber =NewAtomicinteger (1); 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; } }
Write a simple example below.
Packagecom.test; ImportJava.util.concurrent.ExecutorService; Importjava.util.concurrent.Executors; Importjava.util.concurrent.ThreadFactory; classTaskImplementsrunnable{inttaskId; PublicTask (inttaskId) { This. taskid=taskId; } @Override Public voidrun () {System.out.println (Thread.CurrentThread (). GetName ( )+ "--taskid:" +taskId); } } classDaemonthreadfactoryImplementsthreadfactory {@Override Publicthread Newthread (Runnable r) {thread T=NewThread (R); T.setdaemon (true); returnT; } } Public classThreadfactorytest { Public Static voidMain (string[] args) {Executorservice exec=executors.newfixedthreadpool (3,Newdaemonthreadfactory ()); for(inti=0;i<3;i++) {Exec.submit (NewTask (i)); } exec.shutdown (); } }
The output is as follows: thread-0--taskid:0
Thread-1--taskid:1
Thread-2--taskid:2 Analysis: The Newthread () method in Daemonthreadfactory and the invocation relationship of the Submit () method, that is, how daemonthreadfactory works. Debug outputs its invocation relationship: that is, the Newthread () method of the Daemonthreadfactory class is called when submit () to create the thread.
Java Threadfactory Interface Usage