Two Laptop Bag*
The moose likes Beginning Java and the fly likes Threads : Wait() and wait(milliseconds) ?? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Threads : Wait() and wait(milliseconds) ??" Watch "Threads : Wait() and wait(milliseconds) ??" New topic
Author

Threads : Wait() and wait(milliseconds) ??

mani manisha
Greenhorn

Joined: Apr 21, 2011
Posts: 8
in the book :

Given:

1. public class WaitTest {
2. public static void main(String [] args) {
3. System.out.print("1 ");
4. synchronized(args){
5. System.out.print("2 ");
6. try {
7. args.wait();
8. }
9. catch(InterruptedException e){}
10. }
11. System.out.print("3 ");
12. }
13. }

What is the result of trying to compile and run this program?

D is correct. 1 and 2 will be printed, but there will be no return from the wait call because no other thread will notify the main thread, so 3 will never be printed. It's frozen at line 7.


it works as stated. Prints 1,2 and stops forever.... (because nobody notified it!)

now,, i tried replacing wait() with wait(1000)....
this prints 1 2 (pause) 3....
Does this mean that the overloaded wait with one argument goes directly to runnable state after waiting for 1000 millisecs?
Does it not wait for someone to notify(), after the specified arg time is over?


Thanks in advance.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14074
    
  16

Yes, the documentation of the wait(long) method in class Object explains this:
java.lang.Object wrote:
Causes the 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.

So, if nobody has notified it within 1000 milliseconds, it stops waiting and continues running anyway, and "3" will be printed.

p.s. About which book are you talking?

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
mani manisha
Greenhorn

Joined: Apr 21, 2011
Posts: 8
Thanks a lot Jesper de Jong .. appreciate your quick help..

the book is :
SCJP Sun Certified Programmer for Java 6 Study Guide (Exam 310-065)
by Kathy Sierra and Bert Bates
 
Consider Paul's rocket mass heater.
 
subject: Threads : Wait() and wait(milliseconds) ??
 
Similar Threads
thread question in k&b's book for 1.5
Threads, wait method an spurious wakeup
Threads - What will be the correct explination?
Threads notify() and notifyAll()
Thread question