Java Multi-Thread-----implement your own threadfactory

Source: Internet
Author: User

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

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.