I understand that if I create some variable inside the loop in main thread, it will create one, then at next iteration it will create another one with the same name and it will continue till loop is done. No problem, because each iteration the variable which was created is gone, so we can create another one.
But what if I create threads with the same name in the loop. Threads doesn't "terminate" at the same time. So why it's possible? I feel like I should separate JVM work with creating variables and OS work with handling the threads, but want to hear a proper explanation.
for (int i = 0; i < 10; i ) {
MyFirstThread thread = new MyFirstThread();
thread.start();
}
CodePudding user response:
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.
CodePudding user response:
You just assign reference to the new custom object MyFirstThread
to the new variable thread
. In the each cycle of the loop variable thread
go out of scope and you loose reference to the MyFirstThread
and new variable thread
created.