posted 22 years ago
The question is
----------------
class A extends Thread {
public void run() {
try {
synchronized (this) {
wait();
}
} catch (InterruptedException ie) {
System.out.print(interrupted());
}
}
public static void main(String[] args) {
A a1 = new A();
a1.start();
a1.interrupt();
}
}
is it possible that before a1 has got the opportunity to run, a1.interrupt is called?
------
Yes it is possible .
------------
in that case what wud happen for the wait called in run() method and the out put for as a result?
----------
In that case wait() method will retun immediately and exception will be handled.Since you used System.out.xxx in the exception handling section(exception handling will clear the interrupt status first),
System.out.print(interrupted());
it will result "false".
If the code looks like following, the result would have been "true " followed by "false".
class A extends Thread {
public void run() {
try {
synchronized (this) {
System.out.print(isInterrupted());
wait();
}
} catch (InterruptedException ie) {
System.out.print(isInterrupted());
}
}
public static void main(String[] args) {
A a1 = new A();
a1.start();
a1.interrupt();
}
}
Note : interrupted() clears the interrupt status after its call. So calling it twice for a interrupted thread will result "true false" isInterrupted() does not clear the interrupt status.
You can excute this few times, you will see the result yourself.
Ambapali