I can't seem to understand how these two segment of lines interact.
while (true) {
Thread current = currentThread();
System.out.println(this);
public String toString() { return "#" + getName() + ": " + countdownIndex;
}
The program is blank without the first segment, but if the second segment is commented out, it prints out this:
Thread[1,5,main]
Thread[1,5,main]
Thread[1,5,main]
Thread[1,5,main]
Thread[2,5,main]
Thread[2,5,main]
Thread[2,5,main]
Thread[2,5,main]
Thread[3,5,main]
Thread[3,5,main]
Thread[3,5,main]
Thread[3,5,main]
Thread[4,5,main]
Thread[4,5,main]
Thread[4,5,main]
Thread[4,5,main]
I don't understand the sequence. How does the toString() method interact with the data, if it comes later in the program? Also, what does the above print out mean? Why the 5's and the main? I understand that the ascending numbers are each thread.
print statement and to string method
Under discussion
Comments (3)
- Popular
- New
- Old
You must be signed in to leave a comment
Thomas
9 July 2021, 05:35
If you print an object, then the toString method is implicitely called on that object. Cause of polymorphism overriden toString methods get called if they exist, if not the methods of ancestor classes.
Here you have the inheritance chain Object - Thread - SleepingThread, Each has a toString method and if you create a SleepingThread object and print it, it's toString method is invoked (and it doesn't matter where in the code inside the SleepingThread class you define that method). If you comment out (delete) SleepingThreads toString method and then print it, toString of Thread is called instead.
If you now look at the Java Api documentation for Thread and read what that method outputs you'll see:
public String toString()
Returns a string representation of this thread, including the thread's name, priority, and thread group.
So it'll output thread names (here you assigned threadCount as name), the priority (depends on the JVM, here 5 - you can check that yourself with getPriority) and the last info is the thread group. You spawned the threads from the main thread and you haven't assigned another group so it's in the main group.
+1
Ryan Palmer
12 July 2021, 02:41
It took me a few reads, but I get it! Interesting. So using the keyword "this" calls the object to be printed, which really calls the toString method for the SleepingThread. That cleared it up!
0
Thomas
12 July 2021, 05:23
yep, I know, my explanations are sometimes hard to understand ;) But as long as you get it in the end it's OK (at least I hope so).
this is the reference to the object. You not only can print this, you even could return the reference to a caller and use that reference somewhere else in your code like (assume the objects type is Cat and the code is inside the class definition):
good luck with your further studies ;) +1