This article is a summary of the study of the article on the network, thank you for your selfless sharing.
1 , Factory mode is the most useful design mode. It is a creative model, and his purpose is to create objects of one or several classes of objects. With this factory, we have these advantages. Focus on creating objects:
It's easier to change the way objects are created or created by the class.
It is simpler to restrict the creation of objects in order to limit the resources.
Simpler generation of statistics that create objects.
2 , Java provides an interface that threadfactory interface implements a thread object factory
Package Chapter;import Java.util.arraylist;import java.util.date;import java.util.iterator;import java.util.List; Import Java.util.concurrent.threadfactory;public class Mytreadfactory implements threadfactory{private int counter; private string Name;private list<string> stats;public mytreadfactory (String name) {counter = 0;this.name = name; Stats = new arraylist<string> ();} @Overridepublic thread Newthread (Runnable r) {Thread t = new Thread (r,name+ "_thread_" +counter); Counter++;stats.add ( String.Format ("Created thread%d with name%s on%s\n", T.getid (), T.getname (), New Date ())); return t;} Public String getstatuts () {StringBuffer buffer = new StringBuffer ();iterator<string> it = Stats.iterator (); It.hasnext ()) {Buffer.append (It.next ()); Buffer.append ("\ n");} return buffer.tostring ();}}
Package Chapter;import Java.util.concurrent.timeunit;public class Task12 implements runnable{@Overridepublic void Run ( {try {TimeUnit.SECONDS.sleep (1);} catch (Interruptedexception e) {e.printstacktrace ()}}}
Package Chapter;public class Main12 {/** * <p> * </p> * @author Zhangjunshuai * @date 2014-8-25 pm 6:58:42 * @p Aram args */public static void main (string[] args) {Mytreadfactory factory = new Mytreadfactory ("Mytreadfactory"); Task12 task = new Task12 (); Thread thread; System.out.println ("Starting the Threads"); for (int i = 0; I < 10; i++) {thread = Factory.newthread (Task); Thread.Start ();} System.out.println ("Factory stats:"); System.out.printf ("%s\n", Factory.getstatuts ());}}
Run effect
Ten Java Concurrent Learning-creating threads with Thread factory