I have some code that demonstrates the use of threads by the use of the Runnable interface. I started with code off a website somewhere, and modified it to my liking. It works, but I don't understand part of it. I tried to strip the code down to the essence of what I am asking, but I may have taken too much out. The code I have in NetBeans works, so this is working code, unless I messed it up by taking the wrong thing out. But let me ask my question, and see if it can be answered regardless: The part I don't understand is this part:
public String toString()
{
return "Thread " + Thread.currentThread().getName() + ": " + countDown;
}
For the longest time, this just looked to me like a member variable whose name is dynamically set at runtime equal to the name of the current thread. But I have also read in more than one place that you cannot dynamically name variables in Java, so I guess that isn't what I'm looking at. Then, I realized that NetBeans wanted me to put @Override right before this code section, because something is being overridden. But I don't understand exactly what is being overridden. Am I overriding the constructor of some parent class? If so, what class?
Anyway, here is the code:
package countdown;
public class Counter implements Runnable
{
private int countDown = 5;
public String toString()
{
return "Thread " + Thread.currentThread().getName() + ": " + countDown;
}
public void run()
{
while(true) {
System.out.println(this);
if(--countDown == 0)
{
return;
}
}
}
}
package countdown;
public class Main
{
public static void main(String[] args)
{
for(int i = 1; i <= 5; i++)
new Thread(new Counter(), "" + i).start();
}
}