Object类中的wait(),notify(),notifyAll()用于线程的等待唤醒,都必须在synchronized内部中执行,否则会抛出异常Exception in thread “Thread-0” Exception in thread “Thread-1” java.lang.IllegalMonitorStateException。
唤醒后等待会导致线程一致阻塞。
publicclassObjectWaitNotify{static Object objectLock =newObject();publicstaticvoidmain(String[] args){newThread(()->{try{
TimeUnit.SECONDS.sleep(3);}catch(InterruptedException e){
e.printStackTrace();}synchronized(objectLock){
System.out.println(Thread.currentThread().getName()+"\tcome in");try{
objectLock.wait();}catch(InterruptedException e){
e.printStackTrace();}
System.out.println(Thread.currentThread().getName()+"\t被唤醒");}}).start();newThread(()->{synchronized(objectLock){
objectLock.notify();
System.out.println(Thread.currentThread().getName()+"\t通知");}}).start();}/**
* 正常执行:
* Thread-0 come in
* Thread-1 通知
* Thread-0 被唤醒
*
* 去除同步代码块(synchronized)之后:Exception in thread "Thread-0" Exception in thread "Thread-1" java.lang.IllegalMonitorStateException
*
* 先通知后等待:线程永久阻塞无法唤醒
* Thread-1 通知
* Thread-0 come in
*/}