| Author |
getting java.lang.IllegalMonitorStateException: current thread not owner .
|
subuhi nigar
Greenhorn
Joined: Aug 28, 2012
Posts: 12
|
|
I am new to multithreading .
I am getting Exception in thread "main" java.lang.IllegalMonitorStateException: current thread not owner .
below is my code .
NewTask nw = new NewTask(1);
nw.start();
try{
nw.wait(2000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
I want to wait thread nw for few seconds after starting .
I changed wait(5000) to nw.sleep(5000); then it doesn't give any problem . by watching current thread not owner it seems nw is not the thread that is going to wait !!
I wonder whether wait(long) will pause the executing thread or the Thread of which object is called.
Can any body explain me .. when to use wait(long) & when to use sleep(long) ?
Thanks in advance .
|
 |
Steve Luke
Bartender
Joined: Jan 28, 2003
Posts: 3027
|
|
Both nw.wait() and nw.sleep() cause the current thread to pause execution, not the thread on which you you call them. There is no way to cause a different thread to pause.
The nw.wait() call is used to pause the current thread's execution for a period of time or until another thread notifies it to continue. It is used for inter thread communication and must be inside a synchronized block where you synchronize on the same object you call wait on (wait is a method in the Object interface, not Thread, so any and every Object can be used for synchronization and wait()ing.)
Thread#sleep() is a static method in Thread which pauses the current thread of execution for a fixed period of time.
|
Steve
|
 |
 |
|
|
subject: getting java.lang.IllegalMonitorStateException: current thread not owner .
|
|
|