Based on your comments it sounds like you are doing something like this:
Thread thread = new Thread(new Runnable(){
public void run() { // do stuff }});
thread.start();
...
thread.wait();
There are three problems.
As others have said, obj.wait()
can only be called if the current thread holds the primitive lock / mutex for obj
. If the current thread does not hold the lock, you get the exception you are seeing.
The thread.wait()
call does not do what you seem to be expecting it to do. Specifically, thread.wait()
does not cause the nominated thread to wait. Rather it causes the current thread to wait until some other thread calls thread.notify()
or thread.notifyAll()
.
There is actually no safe way to force a Thread
instance to pause if it doesn't want to. (The nearest that Java has to this is the deprecated Thread.suspend()
method, but that method is inherently unsafe, as is explained in the Javadoc.)
If you want the newly started Thread
to pause, the best way to do it is to create a CountdownLatch
instance and have the thread call await()
on the latch to pause itself. The main thread would then call countDown()
on the latch to let the paused thread continue.
Orthogonal to the previous points, using a Thread
object as a lock / mutex may cause problems. For example, the javadoc for Thread::join
says:
This implementation uses a loop of
this.wait
calls conditioned onthis.isAlive
. As a thread terminates thethis.notifyAll
method is invoked. It is recommended that applications not usewait
,notify
, ornotifyAll
onThread
instances.