Factory mode is one of the most commonly used patterns, and of course we can use Factory mode to produce thread when creating threads, which can replace the default
And in a custom factory, we can create custom thread and count, or limit the number of thread creation,
To each thread to set the corresponding good name, or a lot of other things, in short, is very cool, let's show a simple thread
Factory mode to create your own thread.
Package Com.bird.concursey;import Java.util.arraylist;import Java.util.date;import java.util.iterator;import Java.util.list;import Java.util.concurrent.threadfactory;public class Mythreadfactory implements ThreadFactory { private int counter;private string name;private list<string> stats;public mythreadfactory (String name) {counter = 0 ; this.name = Name;stats = new arraylist<string> ();} @Overridepublic thread Newthread (Runnable run) {Thread t = new Thread (run, name + "-thread-" + counter); counter++;stats.ad D (String.Format ("Created thread%d with name%s on%s\n", T.getid (), T.getname (), New Date ())); return t;} Public String Getstas () {StringBuffer buffer = new StringBuffer ();iterator<string> it = Stats.iterator (); It.hasnext ()) {Buffer.append (It.next ()); Buffer.append ("\ n");} return buffer.tostring ();} public static void Main (string[] args) {Mythreadfactory factory = new Mythreadfactory ("Mythreadfactory"); Task task = new Task (); Thread thread = null;for (int i = 0; i <10; i++) {thread = Factory.newthread (Task); Thread.Start ();} System.out.printf ("Factory stats:\n"); System.out.printf ("%s\n", Factory.getstas ());}}
Java Multi-Thread-----implement your own threadfactory