aspose file tools
The moose likes Threads and Synchronization and the fly likes Question related to wait and sleep Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Reply Bookmark "Question related to wait and sleep" Watch "Question related to wait and sleep" New topic
Author

Question related to wait and sleep

Sandeep Kumar B
Ranch Hand

Joined: Jul 10, 2011
Posts: 40


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

Joined: Jun 10, 2011
Posts: 207

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.


Piyush
Pankaj Kumarkk
Ranch Hand

Joined: Apr 17, 2011
Posts: 108
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.
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Question related to wait and sleep
 
Similar Threads
wait() will wait forever
Using wait/notify()
Threads and locks
wait() and join()
Thread wait() and notify()