File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes K&B thread question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "K&B thread question" Watch "K&B thread question" New topic
Author

K&B thread question

H. Ali
Greenhorn

Joined: Feb 25, 2011
Posts: 21
This question is on page 777

What is the result of this code?
A. It prints X and exits
B. It prints X and never exits
C. It prints XY and exits almost immeditately
D. It prints XY with a 10-second delay between X and Y
E. It prints XY with a 10000-second delay between X and Y
F. The code does not compile
G. An exception is thrown at runtime
Answer:
􀀂 ✓ G is correct.The code does not acquire a lock on t before calling t.wait(), so it throws an
IllegalMonitorStateException. The method is synchronized, but it's not synchronized
on t so the exception will be thrown. If the wait were placed inside a synchronized(t)
block, then the answer would have been D.


hi
i understand the answer
but let's (assume) that the code is correct and would compile
as you can see we didn't override the run() method....we used the one in the Thread class and it doesn't print anything
but when we did t.start() the run() method still ran even though nothing is printed....so after that isn't the thread t supposed to be dead??? i mean we did call t.wait() after that and i believe that the thread would be dead by that time???
so what do you think?
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 19070
    
  40

Jose Armando wrote:
i understand the answer
but let's (assume) that the code is correct and would compile
as you can see we didn't override the run() method....we used the one in the Thread class and it doesn't print anything
but when we did t.start() the run() method still ran even though nothing is printed....so after that isn't the thread t supposed to be dead??? i mean we did call t.wait() after that and i believe that the thread would be dead by that time???
so what do you think?


The wait() and notify() methods are methods of the Object class; it is not specific to the Thread class.

This example happens to wait on an instance of the Thread class, but arguably, you would get the same run time error, if you don't synchronize the instance, no matter what instance you use.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: K&B thread question