This week's book giveaway is in the Cloud/Virtualizaton forum.
We're giving away four copies of Mesos in Action and have Roger Ignazio on-line!
See this thread for details.
Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
mani manisha
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 15284
39
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
mani manisha
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic