Page 1 of 1

Re: enthuware.ocpjp.v7.2.1336

Posted: Wed Feb 25, 2015 9:51 am
by ThufirHawat
The right answer "Second will never be printed before First".
I'm sure is wrong, I ran 5 times this code, and the order is random.

The answer should be
"It may print First, Second and MyRunnable in any order."

Please confirm.

Re: enthuware.ocpjp.v7.2.1336

Posted: Wed Feb 25, 2015 11:35 am
by admin
Given answer is correct. Kindly read the explanation.

Re: enthuware.ocpjp.v7.2.1336

Posted: Sun Mar 17, 2019 2:56 pm
by crazymind

Code: Select all

"Thread.currentThread().setName("Second")"
Hi, Which thread's name was set to Second in this code? Is main thread (First) or MyRunnable? Thanks.

Re: enthuware.ocpjp.v7.2.1336

Posted: Sun Mar 17, 2019 9:29 pm
by admin
Thread.currentThread() gives you the reference to whichever thread executes this statement. So, in this case, it is the main thread.
Also, there is no MyRunnable thread. In fact, there is only one thread, the main thread, in this program. No other thread is created.

Re: enthuware.ocpjp.v7.2.1336

Posted: Mon Mar 18, 2019 11:05 am
by crazymind
admin wrote:
Sun Mar 17, 2019 9:29 pm
Thread.currentThread() gives you the reference to whichever thread executes this statement. So, in this case, it is the main thread.
Also, there is no MyRunnable thread. In fact, there is only one thread, the main thread, in this program. No other thread is created.
Now there are two threads running (or ready to run state): The main thread (having the name "First") and the MyRunnable thread (having the name "MyRunnable"). Any of these two threads may be allowed to run by the OS.
This is from the solution of this question. I am kind of confused.

Re: enthuware.ocpjp.v7.2.1336

Posted: Mon Mar 18, 2019 11:35 am
by admin
Sorry, I saw a different question that was similar. The explanation given in the question is correct.
But the answer that I gave to your query is still the same - Thread.currentThread() gives you the reference to whichever thread executes this statement. So, in this case, it is the main thread who name is being by the statement Thread.currentThread().setName("Second").