The first step is to build the thread wrapper class Workthread, which is primarily designed to enable better management of threads
public class workthread extends thread { private runnable target; //Thread Execution Target private atomicinteger counter ; public workthread (Runnable target, atomicinteger counter) { this.target = target; this.counter = counter; } @Override Public void run () { try { target.run (); } finally { int c = counter.getanddecrement (); system.out.println ("terminate no " + c + " Threads "); } } }
Second, to define a test target
public class Workrunnable implements runnable{@Overridepublic void Run () {System.out.println (' complete a Task ');}}
Ways to implement a threading factory
public class Workthreadfactory implements threadfactory{private Atomicinteger Atomicinteger = new Atomicinteger (0); Overridepublic Thread Newthread (Runnable r) {int c = atomicinteger.incrementandget (); System.out.println ("Create no" + C + "Threads"); return new Workthread (R, Atomicinteger);//counter to better manage threads}}
Test Thread Factory
Public class testthreadfactory {public static void main (String[] args) {//Create thread (concurrency) pool, auto scale (automatic conditional thread pool size) Executorservice es = executors.newcachedthreadpool (new workthreadfactory ());//Concurrent with 5 worker threads Es.execute (new workrunnable ()); Es.execute (New workrunnable ()) ; Es.execute (New workrunnable ()); Es.execute (New workrunnable ()); Es.execute (New workrunnable ()); /indicates that the thread pool and worker threads are closed when all threads have finished executing, and if this method is not called, the JVM does not automatically shut down es.shutdown (); try { //wait for the thread to finish executing, not more than 2*60 seconds, with shutdown Es.awaittermination (2*60, timeunit.seconds); } catch ( Interruptedexception e) { e.printstackTrace (); } }}
Java uses threadfactory to create a new thread