You're mixing up objects (class instances) and variables. These are two completely different things in Java.
You can create objects with the new
operator, as in new MyFirstThread()
. From that point on, they exist "forever", until the garbage collector finds that they are no longer needed, which, for a Thread will not happen before it's finished.
A variable can contain a reference to an object. And as long as an object is referenced by a variable, the garbage collector will not touch it.
Now, in your code
for (int i = 0; i < 10; i++) {
MyFirstThread thread = new MyFirstThread();
thread.start();
}
A valid (but simplified) interpretation is that you ten times
- create a variable named
thread
,
- create an object of class
MyFirstThread
and store a reference to that object in the variable,
- start that thread,
- dispose of the variable
thread
(when execution hits the }
end of the iteration = end of scope of the variable).
The key point is that disposing of a variable does not affect the object that it referenced. As long as there's a reason for this object to continue its existence (e.g. the thread still running), it will stay alive and continue to do its job.
While in the loop, e.g. in the second iteration, the first thread
variable no longer exists, but the first MyFirstThread
instance still exists and runs.
Analogy:
Imagine MyFirstThread instances to be houses, and variables to be sheets of paper where you note the house address.
Then you do ten times:
- take a fresh sheet of paper,
- build a house in some location and write down the address on the sheet of paper,
- using the address from your sheet, order someone to continuously mow the lawn (sorry, not a perfect analogy),
- throw away the sheet of paper.
In the end, there will be ten houses with perfect lawns, but you will not be able to access them, as you no longer know how to find them.