OK, so the object "thread"'s life cycle is up to the method buttonClicked
, so if the method return, object thread will be destroy even if thread.start()
is still running?
I see two missunderstandings here:
If the method buttonClicked
returns, the reference to the object will be gone. The object instance of NewThread
will be still alive until no one references it and additionally a garbage collector decides to reclaim that memory. This means, that the instance of NewThread
will be there at least as long as the run()
method of NewThread
is running because the stack of the thread which is described by the NewThread
instance references that instance. That stack will be cleared when run()
terminates.
thread.start()
will return immediately. It only signals the second thread to start working.
Assume buttonClicked() will be invoke when we click a button, so I click the button several times, every time I click it, a new Object thread will be created, so in this case, there are many different "NewThread" Object exist in JVM?
In fact you are accumulating NewThread
instances if the run()
method of NewThread
is slow compared to your click rate.
I do like this, then JVM crash.
You mean you like clicking buttons and the following JVM crash? ;-)
Edit: After the question has been changed/extended, a third point appeared:
In buttonClicked()
method, before invoke thread.abc();
if thread.start()
is already finished, can i still invoke the thread object thread.abc();
?
Of course you can invoke any method on an object as long as you have a reference. Thread
is no exception here.
I think the main difficulty you have is this: The reference thread
points to an object. This object is not the real thread (note the small t), it is only some small memory area with some descriptions about the real thread. The real thread consists of some CPU settings, the OS scheduler stuff, a stack and so on.
The lifetimes of these two things, the object and the real thread, are not coupled strictly: The object Thread
exists before the real thread is created (which happens inside Thread.start()
). The real thread dies after leaving the run()
method. But the object Thread
exists even after that up to the point when normal garbage collection kicks in as already described.