• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt in the output of the thread program

 
Dhivya rajagopal
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


OUTPUT:
5
4
3
2
1
New name is:Thread[Second Thread,5,main]

In the above line, how 5 comes. It is given that ,its priority is 5,which is the default value. I don't understand this statement. Can you please explain how the result came.

[Edit: added code tags - MB]

 
Harsha Smith
Ranch Hand
Posts: 287
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
.toString() method is called and .toString() on a thread object

Returns a string representation of this thread, including the thread's name, priority, and thread group.

instead of Thread.sleep() use java.util.concurrent.TimeUnit. increases the readability of your code greatly

Ex: TimeUnit.SECONDS.Sleep(1);
 
Dhivya rajagopal
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Thank you smith.I asked how 5(priority) comes in the output. That is in New name is:Thread[Second Thread,5,main]. Still i cant understand . Thank you for telling about TimeUnit
 
Rob Spoor
Sheriff
Pie
Posts: 20610
63
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's simply how Thread's toString() method is written - it prints the name, priority and thread group name.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49796
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rob and Harsha Smith have told you that is what toString on a Thread returns. You can see for yourself if you find the documentation.
 
Harsha Smith
Ranch Hand
Posts: 287
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
.toString() method is called and .toString() on a thread object

Returns a string representation of this thread, including the thread's name, priority, and thread group.


Default priority for any thread object is 5; thats how it appeared in the output.

try printing threadMain.getPriority();

you can set priorities to the threads using setPriority(int priority) method. Always use priority constants provided by the class Thread(Ex: Thread.MAX_PRIORITY)

try printing the following lines of code

System.out.println(Thread.NORM_PRIORITY);//default priority 5
System.out.println(Thread.MAX_PRIORITY);//returns 10
System.out.println(Thread.MIN_PRIORITY);//returns 1


 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic