Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
TimeUnit.SECONDS.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread.start();
try {
thread.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("end");
}
this sentence will throw :
Exception in thread "main" java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
but use “thread.join()” to replace “thread.wait(0)’ doesn’t throw any exception.
The puzzle is
I query the thread.join() source code: it will go to :
while(isAlive)
wait(0);
it means they both trigger wait(0). but why the result is so different?
Take another look at the source code and you will find the join is done while holding the monitor ( while synchronized ). If you want to use “thread.wait(0)” you need to wrap it in a synchronized block or method.
Have a look at: http://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html
and so in your code try