About Question enthuware.ocpjp.v17.2.3740 :
Moderator: admin
-
- Posts: 167
- Joined: Sun Apr 21, 2024 10:43 am
- Contact:
About Question enthuware.ocpjp.v17.2.3740 :
it gives me 10 all the time and 10 is not correct answear why?
Online
-
- Site Admin
- Posts: 10384
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: About Question enthuware.ocpjp.v17.2.3740 :
Did you read the detailed explanation provided with the question? Let us know which part is not clear so that we can help.
-
- Posts: 167
- Joined: Sun Apr 21, 2024 10:43 am
- Contact:
Re: About Question enthuware.ocpjp.v17.2.3740 :
ok so here is what i learned
with this code it will always print 5 because the main Thread will wait the other tr thread to finish and change x value to 5
in this code i added join() but without join() main Thread is not waiting for other tr thread to finish it's execution so main Thread will immediatly execute the System.out.println and show 10
that's why i don't understand why The output cannot be determined because i always get 10 when i run the code on my machine
Code: Select all
TestClass tc = new TestClass();
tc.x = 10;
Thread tr = new Thread(tc);
tr.start();
tr.join();
System.out.println(tc.x);
in this code i added join() but without join() main Thread is not waiting for other tr thread to finish it's execution so main Thread will immediatly execute the System.out.println and show 10
that's why i don't understand why The output cannot be determined because i always get 10 when i run the code on my machine
Online
-
- Site Admin
- Posts: 10384
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: About Question enthuware.ocpjp.v17.2.3740 :
Your understanding about join is incorrect. When the main thread calls tr.join(), that just means the main thread will wait for the other thread to finish before executing the next statement but that doesn't mean all statements appearing in the tr thread will be executed after all of the statements appearing in the main thread before the call to join.
The main thread has its set of instructions and the tr thread has its set of instructions. Instructions in both of these sets can actually be executed in any order unless the two threads use some synchronisation mechanism.
The main thread has its set of instructions and the tr thread has its set of instructions. Instructions in both of these sets can actually be executed in any order unless the two threads use some synchronisation mechanism.
-
- Posts: 167
- Joined: Sun Apr 21, 2024 10:43 am
- Contact:
Re: About Question enthuware.ocpjp.v17.2.3740 :
thank you sir i understand better now the code of the question because the Thread Scheduler decide and its unpredictable
Who is online
Users browsing this forum: admin and 11 guests