The join method is called on instance of a thread object. For your reference check the API
posted 10 years ago
but on which.
I'm wondering cause I was told that the output will 3. So this invocation has to ensure that run-method will run before doSomething adds 1 and prints out i. What's the order of execution? Or as we're talking about Threads, What could be the order?
Does this mean that in case of two running threads join() waits for the other one to finish, or what? What if we have multiple threads???
As you can see, I'm a bit confused...
Thanks in advance, Andreas [ August 15, 2008: Message edited by: Andreas Auer ]
this is really tricky question, I try to explain you how it works. In this line
main thread creates the object of MyClass - at this point the constructor of MyClass is called. In the constructor value of i is initialized (i=1), then the start() method starts a second thread (start() is implicity called on 'this' object). Main thread continues to execute, returns from the constructor and then the doSomething() method of MyClass object is called (by main thread). In doSomething() main thread calls join() method - implicitely on 'this' object. 'this' is the reference to MyClass object (second thread object), so at this point main thread is paused and waits for the second thread to finish. The second thread calculates the value of 'i' field (i=2) and finishes. Next, main thread 'wakes up', adds 1 to i (at this point i=2) and prints value of i .... i = 3.
Hope that this is clear enough. [ August 15, 2008: Message edited by: Ireneusz Kordal ]