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 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 "thread question" Watch "thread question" New topic
Author

thread question

Harvinder Singh
Ranch Hand

Joined: Feb 14, 2003
Posts: 90
//compiles but gives a runtime exception that thread is not the owner
Question 22)
Which statement is true of the following code?
public class Agg{
public static void main(String argv[]){
Agg a = new Agg();
a.go();
}
public void go(){
DSRoss ds1 = new DSRoss("one");
ds1.start();
}
}
class DSRoss extends Thread{
private String sTname="";
DSRoss(String s){
sTname = s;
}
public void run(){
notwait();
System.out.println("finished");
}
public void notwait(){
while(true){
try{
System.out.println("waiting");
wait();
}catch(InterruptedException ie){}
System.out.println(sTname);
notifyAll();
}
}

}
1) It will cause a compile time error
2) Compilation and output of "waiting"
3) Compilation and output of "waiting" followed by "finished"
4) Runtime error, an exception will be thrown


Hard work beats talent<br />when talent doesn't work hard.<p> - Tim Notke
Jose Botella
Ranch Hand

Joined: Jul 03, 2001
Posts: 2120
Hi,
never call notify or wait out of a synchronized block/method. There will be a RuntimeException, thus answer is 4)
To avoid the IllegalMonitorStateException the thread that calls object.notify() must also have entered a synchronized block like:
synchronized(object) {
..
object.notify();
}
or be executing a synchronized method of object. By either of these techniques the thread executing object.notify() is owner (has adquired) the monitor of object.
Please see The Java Tutorial for more.


SCJP2. Please Indent your code using UBB Code
 
Consider Paul's rocket mass heater.
 
subject: thread question