File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

thread question

 
Harvinder Singh
Ranch Hand
Posts: 90
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
//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
 
Jose Botella
Ranch Hand
Posts: 2120
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic