To create a thread with a thread factory

Source: Internet
Author: User
Tags log log

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.