• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

K&B thread question

 
H. Ali
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 21493
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic