Reputation: 165
Anybody can explain why this program is giving output 9? I guessed "unpredictable behavior" as its answer since main thread and thread-0 can execute in any sequence. What will join() do on main thread itself?
public class Starter extends Thread{
private int x = 2;
public static void main(String[] args) throws Exception{
new Starter().makeItSo();
}
public Starter(){
//Thread main
x=5;
start();
}
public void makeItSo() throws Exception{
//Thread main
join();
x = x-1;
System.out.println(x);
}
public void run(){
//Thread-0
x*= 2;
}
}
Main thread starts the thread-0 and calls the run method. but if you put SOP in makeItSo(), it says that main thread is waiting there after call to join()! why? What I thought there will be no sequence between makeItSo() or run() so value of X will be unpredictable.
Upvotes: 1
Views: 1188
Reputation: 1
I believe that the confusion is caused by the way join() is called - because it's invoked from an instance method, it's like saying this.join(), where 'this' references the Starter object that was created in the main method.
This means that the main thread waits for the Starter thread to terminate and after that it decreases the value of x. This is way the result is very predictable.
Upvotes: 0
Reputation: 5657
For really deep understanding this you should read 17.4.4 Synchronization Order
from java language specification, that says:
Synchronization actions induce the _synchronized-with_ relation on actions,
defined as follows:
...
- An action that starts a thread _synchronizes-with_ the first action in the
thread it starts.
...
- The final action in a thread *T1* _synchronizes-with_ any action in another
thread *T2* that detects that *T1* has terminated. *T2* may accomplish this
by calling *T1.isAlive()* or *T1.join()*.
Upvotes: 1
Reputation: 2323
The order of execution here is fixed, because of the call to join()
:
x = 5
.start
which in turn calls run
in a new thread.run
executes x *= 5
, making x
equal to 10.makeItSo
is called. It calls join
, thus waiting for run
to end.makeItSo
sets x = x-1
, making x
equal to 9.Upvotes: 6
Reputation: 14277
You first create Starter object. In constructor you have x = 5
. Than you call start()
, which internally calls run()
. After run your x is 10 (x *= 2
). Your join()
waiting run()
to finishes, and after that you decrement x by 1 and that's it. x is 9. There is really nothing unpredictable here.
Upvotes: 0