• Post Reply Bookmark Topic Watch Topic
  • New Topic

Question related to wait and sleep

 
Sandeep Kumar B
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Please see the below code



Output is always
Waiting for b to complete...
--1--2--3--4--5--6--7--8--9
Total is: 45

As we know that wait(1) will wait for 1 millisecond
From
http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Object.html#wait%28long%29
public final void wait(long timeout)
throws InterruptedException
"Causes current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed. "

I was expecting that since in the loop sleep(100) is more than wait(1), wait statement would stop waiting and print the Total in the middle of the calculation
Why did the program never outputs?

Waiting for b to complete...
--1--2
Total is: 3
--3--4--5--6--7--8--9

etc
I tried changing the sleep to even 1000 but still the same output
 
Piyush Joshi
Ranch Hand
Posts: 207
Eclipse IDE Firefox Browser jQuery
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sandeep Kumar B wrote:
I was expecting that since in the loop sleep(100) is more than wait(1), wait statement would stop waiting and print the Total in the middle of the calculation

but after wait period i.e. 1 miliseconds is over main thread will have to reacquire the lock on ThreadB object b,
so it will block for lock on b to be released, sleep() method call in ThreadB does not cause lock to be released,
so lock of b is still with ThreadB.
 
Pankaj Kumarkk
Ranch Hand
Posts: 112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I do not know what are you trying to achieve. the current behavior is because sleep blocks but doesn't give up monitor. Thus the other thread doesn't get the monitor and doesn't executes.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!