Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question about working of ReentrantLock

 
D Preethi
Ranch Hand
Posts: 68
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

Can someone tell me what I am doing wrong here? The program seems to execute eternally(and does not print DONE) though I am changing the condition of the boolean variable in the thread. Basically, I want the main thread to resume once a condition is satisfied in the thread. How do I achieve that?




Thanks in advance,
Preethi
 
Adam Smolnik
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey.
First of all you must signal the resumed thread with condition.signal().
You remember about very important lock.unlock(s) in finally sections.

Adam

 
D Preethi
Ranch Hand
Posts: 68
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot, Adam!! Currently, there is no way to get the list of all available conditions on a particular lock, right? I just see this API -

Condition c = lock.newCondition();

So, if I want to split the above mentioned code in different classes ( the sleep thread in one class, and the variable monitoring code in another class), I shall need to pass the references to both lock and the condition the first class created, right?
 
Adam Smolnik
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey.

Essentially, I personally would NOT make access locks and conditions outside class without very justified reason.
Next, I would browse existing solutions in java.util.concurrent package like Executors, CyclicBarrier etc..

In case of need, you consider my somewhat other approach to your described problem(semantically should be equivalent):



Results:

Hey there
var = false
var = true
DONE!!!

Adam
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic