• Post Reply Bookmark Topic Watch Topic
  • New Topic

Thread::setName(string)  RSS feed

 
Aby Krishna
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
A quick question, what will happen if i invoke setName(String) API on a thread instance after it has been started via "start()". Will the name be at on the thread and printing it would print the new name? or the name can not be set after the thread has been started?
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If the current thread is allowed to access the thread that you are trying to rename, yes.
 
Abimaran Kugathasan
Ranch Hand
Posts: 2066
Clojure IntelliJ IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Don't you try it? Have a look on this API
 
subodh k kumar
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Yes,Inside your run() method you can access the Current thread and reset the name of it.This will print the new Thread Name.
Thread currentThread = Thread.currentThread();
currentThread .setName("newName");
 
Santosh Kumar Nayak
Ranch Hand
Posts: 193
Eclipse IDE IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Output is :
main
Hello

why t.setName("Hey "); is not able to set the name ?
 
Henry Wong
author
Sheriff
Posts: 23281
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Santosh Kumar Nayak wrote:
why t.setName("Hey "); is not able to set the name ?


Question. When the code runs t.run(), which thread is executing it?

Hint. The output should give you an idea.

Henry
 
Santosh Kumar Nayak
Ranch Hand
Posts: 193
Eclipse IDE IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Got it

t.setName("Hey"); was trying set name to main thread
 
Campbell Ritchie
Sheriff
Posts: 55351
157
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Santosh Kumar Nayak wrote:Got it

t.setName("Hey"); was trying set name to main thread
'Fraid not.
Draw a diagram with the threads each shown by a little box and write the names in each of them. Whenever each thread changes its name, you will have to erase the name and write a new one in. Now work out how many names you will print out. Then see if you can't get that to match your output.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!