The script . Trying to achieve a result using sleep()and interrupt(); which would otherwise be fulfilled wait()andnotifyAll()
Question - I know that this method is not preferred. Can you guys tell me what is wrong by doing this in this below script.
One reason: notifyAll()notify all threads that are looking for a lock for this object. But with interrupt()
we have a call interruption for each waiting thread explicitly.
Another reason is that another thread cannot change the state of the object. Here is the starting thread itself
food=truewhen fishing InterruptedException. But what is wrong with that?
public class _17GuardedBlockWithSleep_Interrupt_Badcase {
static class Person {
volatile boolean food;
public boolean isFood() {
return food;
}
public void setFood(boolean food) {
this.food = food;
}
String name;
Person(String name) {
this.name = name;
}
public synchronized void eatFood() {
while (!isFood()) {
try {
Thread.sleep(1000000000);
} catch (InterruptedException e) {
this.setFood(true);
System.out.println("eatFood() caught InterruptedException");
}
}
System.out.println("got the food.. yummyy..thanks!");
}
public synchronized void provideFood(Thread t) {
this.setFood(true);
t.interrupt();
}
}
public static void main(String[] args) {
final Person kuttappan = new Person("Kuttappan");
Runnable runnable1 = new Runnable() {
@Override
public void run() {
kuttappan.eatFood();
}
};
final Thread t = new Thread(runnable1, "thread1");
t.start();
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(5000);
t.interrupt();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}