Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Threads interview questions  RSS feed

 
Sim Kim
Ranch Hand
Posts: 268
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

One question asked for Thread was : when you call wait() without having notify() or notifyAll() method , the thread should not come out of wait state . But in this code it does come out :



Try running theabove code and you will see the main thread coming out of wait state .

But if the above code is other way round :


Here the child thread is always in wait() state . Can you throw some light ?
 
Mark Herschberg
Sheriff
Posts: 6037
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
While interview questions are allowed in Job Discussion, I think you'll have better luck in the Threads forum.

--Mark
 
Chris Hurst
Ranch Hand
Posts: 443
3
C++ Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not entirely sure I understand the question ...

... but first (I know this isn't the issue in this case) the last time I looked threads can wake up on their own without a notify i.e. you can have 'spurious thread wake up'. The rule I was always told was never invoke wait outside a while, though I again I appreciate thats not the issue here its just the first statement didn't ring exactly true.

... back to the actual code the problem is you end up with two threads and they'll race each other , i.e. when you start the new one you don't have a lock on it I know you acquire a lock on the next line but its possibly too late i.e. the other thread is alive between the start and the synchronized.

Both threads race to get the lock which one wins ;-)you can't predict, although if you write a testbed you'ed probably get the same answer each time.

Hope thats what you were getting at.



Chris
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Although what Chris says is all true, it's not actually the explanation for what you're seeing. Thread objects call notify() on themselves when they exit -- i.e., when their run() methods complete. This is how the join() method is implemented: it wait()s on the Thread itself and watches a boolean "done" flag. So in your first case, wait() returns when the Thread exits because of a notify() call.

In your second case, with the Thread waiting, it never wakes up, because no one calls notify().
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!