Reputation: 11
Here I am using wait() method in try block for the inter communication between threads. I used wait method outside the try block but it was showing exception.
try
{
System.out.println(" why we should use wait() method in try block ");
wait();
}
catch()
{
}
}
Upvotes: 1
Views: 4464
Reputation: 718936
Q: Why should we use wait() method inside the try block?
You use a wait()
inside a synchronized
block or synchronized
method.
synchronized (this) {
while (!this.isTeapot) {
this.wait();
}
System.out.println("I am a teapot");
}
And in another method ...
synchronized (this) {
this.isTeapot = true;
this.notify();
}
Why?
IllegalMonitorStateException
if you don't.But why?
The try
block is not mandatory. Use a try
block if you need to deal with an exception at that level. If not, allow it to propagate. This includes InterruptedException
... though since it is a checked exception, you would need to declare it in the method's throws
clause if you didn't catch it locally. But this is just normal Java exception handling. Nothing special.
For example:
try {
synchronized (this) {
while (!this.isTeapot) {
this.wait();
}
System.out.println("I am a teapot");
}
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
(For an explanation of the above example, see Why would you catch InterruptedException to call Thread.currentThread.interrupt()?.)
Q: Can we use wait() method outside the try block?
You cannot call wait()
outside of a synchronized
block or synchronized
method. (See above.)
The try
block is not mandatory. (See above.)
Upvotes: 3