| 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
|
 |
 |
|
|
subject: thread question
|
|
|