1. Factory mode/Factory
public class Mythreadfactory implements Threadfactory {
private int counter;//Thread count
Private String name;//Thread name
Private list<string> stats;//Thread object information
Public mythreadfactory (String name) {
counter=0;
This.name=name;
Stats=new arraylist<string> ();
}
Instantiating a Thread object
Public Thread Newthread (Runnable r) {
Thread t = new Thread (r,name+ "_thread_" +counter);
counter++;
Saving information when a thread is created
Stats.add (String.Format ("created thread%d with name%s on%s\n", T.getid (), T.getname (), New Date ()));
return t;
}
Returns stats Collection information
Public String getstats () {
StringBuffer buffer=new StringBuffer ();
Iterator<string> It=stats.iterator ();
while (It.hasnext ()) {
Buffer.append (It.next ());
Buffer.append ("\ n");
}
return buffer.tostring ();
}
}
/**
* Thread
*/
public class Task implements runnable{
Log log = Logfactory.getlog (This.getclass ());
public void Run () {
try {
TimeUnit.SECONDS.sleep (1);
Log.debug ("Thread sleep is not error");
} catch (Interruptedexception e) {
E.printstacktrace ();
Log.debug ("Thread sleep is the error in Task");
}
}
}
Call
public class Main {
public static void Main (string[] args) {
Thread Factory
Mythreadfactory factory = new Mythreadfactory ("Mythreadfactory");
New Thread
Task task = new Task ();
Thread thread;
System.out.println ("Start the threads\n");
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.getstats ());
}
}
}
Incidentally, the diary.
Log log = Logfactory.getlog (This.getclass ());
Log.dubug (");
This is the log print under the Common.logging package.
To create a thread with a thread factory