Java 22-5 multi-thread gets and sets the name of the thread object

Source: Internet
Author: User

How do I get the name of a thread object?
Public final String GetName (): gets the name of the Thread.
How do I set the name of a thread object?
Public final void SetName (String name): Sets the name of the thread
How do I get the name of a thread object in a subclass other than the thread class?
public static thread CurrentThread (): returns the currently executing thread object
Thread.CurrentThread (). GetName ()

Public final String GetName (): gets the name of the Thread.

This method is written in the custom thread class, which is also the subclass of Thread:

1  public classMyThreadextendsThread {2 3      public voidRun () {4         5          for(intx = 0; X < 100; X + +){6System.out.println (getName ()+"--"+x);7         }8     }9 Ten}

then, write the test class again:

1  public classMyThreadDemo1 {2 3      public Static voidmain (string[] Args) {4 5         //Create two Thread objects6MyThread MT1 =NewMyThread ();7MyThread mt2 =NewMyThread ();8           9 Mt1.start ();Ten Mt2.start (); one     } a  -}

Results:

thread-1--0
thread-0--0
Thread-0--1
Thread-0--2 ...

As you can see, the default name given to threads in thread is Thread-x

so, Why is the default name thread-x?

First of all, Mythread is a subclass of thread, so we go first with the parameterless construct of Thread:

class extends Thread {    public  MyThread () {        Super();    }

Next look at the source code of the thread about GetName () and SetName ():

1 classThread {2     Private Charname[];3 4      publicThread () {5InitNULL,NULL, "thread-" + nextthreadnum (), 0);6} Walk this Nextthreadnum (),//Look Down. so, get the name from Here: thread-0/-1 ... 7     8     Private voidinit (threadgroup g, Runnable target, String name,9                       LongStackSize) {TenInit (g, target, name, stackSize,NULL);//here again the Init () method is called, see below one     } a      -      Private voidinit (threadgroup g, Runnable target, String name, -                       LongstackSize, AccessControlContext ACC) { the         //Most of the code is Omitted. -          this. Name = Name.tochararray ();//convert the resulting string class thread-0/-1 into a character array and then give the array to private char name[]; -     } -      +      public Final voidsetName (String Name) { -          this. Name =Name.tochararray (); +}//This is the change of the name of the thread itself, directly the name of the input string class, converted to a character array, and then assigned to the private char name[]; a      at      -     Private Static intthreadinitnumber;//0,1,2 -     Private Static synchronized intnextthreadnum () { -         returnthreadinitnumber++;//return 0,1 -     } -      in      public FinalString getName () { -         returnstring.valueof (name); to}//the name you get here is the string class. +}

Public final void SetName (String name): Sets the name of the thread

Method 1: Non-parametric Construction +setxxx () (recommended)

1  public classMyThreadDemo1 {2 3      public Static voidmain (string[] Args) {4 5         //Create two Thread objects6MyThread MT1 =NewMyThread ();7MyThread mt2 =NewMyThread ();8          9// call method Set thread name  mt1.setname ("husky"); Mt2.setname ("samoyed");            a          - Mt1.start (); - Mt2.start (); the         //The result is a simultaneous execution of 2 print 0-1000 threads -     } -  -}

Method 2: take the constructor method to name the thread

  You first have to add the custom thread class:

1      public MyThread () {2    }3     4      public MyThread (String Name) {5         Super (name); 6     }

Because this class does not have a parameter construction method, it must be created to use the parameter construct

The test class can call the constructor directly by Name:

1 New MyThread ("husky"); 2  New MyThread ("samoyed");

What if you want to get the name of the thread object where the Main method resides?
In this case, the thread class provides this method:
public static thread CurrentThread (): returns the currently executing thread object
System.out.println (thread.currentthread (). getName ());

In the test class, add

System.out.println (thread.currentthread (). getName ());

The output is: main, because the Java Execution program defaults to main

Java 22-5 multi-thread gets and sets the name of the thread object

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.