wait()
* Causes the calling thread to wait until another thread calls the {@code
* notify()} or {@code notifyAll()} method of this object. This method can
* only be invoked by a thread which owns this object's monitor; see
* {@link #notify()} on how a thread can become the owner of a monitor.
* <p>
* A waiting thread can be sent {@code interrupt()} to cause it to
* prematurely stop waiting, so {@code wait} should be called in a loop to
* check that the condition that has been waited for has been met before
* continuing.
* <p>
* While the thread waits, it gives up ownership of this object's monitor.
* When it is notified (or interrupted), it re-acquires the monitor before
* it starts running.
* @throws IllegalMonitorStateException
* if the thread calling this method is not the owner of this
* object's monitor.
* @throws InterruptedException
* if another thread interrupts this thread while it is waiting.
该方法的注释说:使调用线程处于wait状态,直到其他线程调用这个Object的notify或者notifyAll才会被唤醒。这个方法只能被拥有这个Object的Monitor才能被调用。一个正在wait的线程能够被调用interrupt方法。
当一个线程处于Wait,它放弃了它自己的Object Monitor,当它被notified或者interrupted的时候,它会在它启动之前重新请求这个monitor
noitify()
* Causes a thread which is waiting on this object's monitor (by means of
* calling one of the {@code wait()} methods) to be woken up. If more than one thread is waiting, one of them is chosen at the discretion of the VM. The chosen thread will not run immediately. The thread
* that called {@code notify()} has to release the object's monitor first.
* Also, the chosen thread still has to compete against other threads that
* try to synchronize on the same object.
* This method can only be invoked by a thread which owns this object's
* monitor. A thread becomes owner of an object's monitor by executing a synchronized method of that object; by executing the body of a {@code synchronized} statement that synchronizes on the object;by executing a synchronized static method if the object is of type {@code Class}.
使得一个正在等待这个Object的Monitor的线程被唤醒。如果超过一个线程正在等待的话,那么就只有一个线程会被唤醒,而这个线程会由VM自己决定。而这个被选择的线程并不会立马就进入run的状态,调用了notify的线程会首先释放这个Object的Monitor。并且,被选择的线程必须完成和其他线程完成对这个Object锁的竞争。这个方法只能被拥有这个Object的Monitor的线程调用。这个线程拥有这个Object的Monitor,通过执行一个同步方法或者一个同步的代码块来获取这个对象的锁,或者通过执行这个对象的Class类来进行同步。
简单来说,也就是在使用wait和notify的时候,需要使用synchoronized代码块将对象进行Monitor操作,这个操作可以是一个同步代码块,也可以是一个同步的方法,也可以用一个class对象进行同步,总之,在调用wait和notify的时候,必须要进行同步。并且在有多个线程处于wait状态的时候,当调用notify的时候,只有一个线程会收到这个消息,如果是notifyAll的话,所有的线程都会进行竞争,最后也只会有一个线程能够获取到资源,但是它也不会立马进行到run的状态,而是进入就绪的状态,等待时间片到它的时候,就可以执行了。而这个线程的选择是靠JVM来自主决定的。
下面举一个例子:
-
错误的例子:使用wait和noitify的时候没有加同步代码块
public class Test { public static void main(String[] args) { Object lock = new Object(); ThreadA threadA = new ThreadA(lock); ThreadB threadB = new ThreadB(lock); threadA.start(); threadB.start(); } private static class ThreadA extends Thread { Object obj; public ThreadA(Object lock) { obj = lock; setName("ThreadA"); } @Override public void run() { super.run(); System.out.println("Start Wait:" + Thread.currentThread().getName()); try { obj.wait(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Wait End:" + Thread.currentThread().getName()); } } private static class ThreadB extends Thread { Object obj; public ThreadB(Object lock) { obj = lock; setName("ThreadB"); } @Override public void run() { super.run(); System.out.println("ThreadB Start:" + Thread.currentThread().getName()); try { Thread.sleep(5000L); } catch (InterruptedException e) { } System.out.println("After ThreadB Sleep 5S"); obj.notify(); System.out.println("ThreadB notify:" + Thread.currentThread().getName()); } } }
运行后的结果为:
-
正确使用wait notify的例子:
public class Test { public static void main(String[] args) { Object lock = new Object(); ThreadA threadA = new ThreadA(lock); ThreadB threadB = new ThreadB(lock); threadA.start(); threadB.start(); } private static class ThreadA extends Thread { Object obj; public ThreadA(Object lock) { obj = lock; setName("ThreadA"); } @Override public void run() { super.run(); System.out.println("Start Wait:" + Thread.currentThread().getName()); try { synchronized (obj) { obj.wait(); } } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Wait End:" + Thread.currentThread().getName()); } } private static class ThreadB extends Thread { Object obj; public ThreadB(Object lock) { obj = lock; setName("ThreadB"); } @Override public void run() { super.run(); System.out.println("ThreadB Start:" + Thread.currentThread().getName()); try { Thread.sleep(5000L); } catch (InterruptedException e) { } System.out.println("After ThreadB Sleep 5S"); synchronized (obj) { obj.notify(); } System.out.println("ThreadB notify:" + Thread.currentThread().getName()); } } }
运行结果:
从正确的结果可以看出,在ThreadA和ThreadB同时启动的时候,ThreadB先运行,然后进入了Sleep,后ThreadA运行,打印出了StartWait,然后处于wait状态,等到ThreadB从Sleep5秒醒来后,调用object.notify,并且打印ThreadB notify,于是通知ThreadA,接着ThreadA获取到了Object的Monitor之后,结束运行。
2.错误的例子
让B线程先启动,并且在B线程执行完之后,再继续执行主线程,之后再启动A线程,此时A线程中会调用wait方法,这时候线程A一直在等待notify而导致程序无法正常结束。
public class Test {
public static void main(String[] args) {
Object lock = new Object();
ThreadA threadA = new ThreadA(lock);
ThreadB threadB = new ThreadB(lock);
threadB.start();
try {
threadB.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
threadA.start();
}
private static class ThreadA extends Thread {
Object obj;
public ThreadA(Object lock) {
obj = lock;
setName("ThreadA");
}
@Override
public void run() {
super.run();
System.out.println("Start Wait:" + Thread.currentThread().getName());
try {
synchronized (obj) {
obj.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Wait End:" + Thread.currentThread().getName());
}
}
private static class ThreadB extends Thread {
Object obj;
public ThreadB(Object lock) {
obj = lock;
setName("ThreadB");
}
@Override
public void run() {
super.run();
System.out.println("ThreadB Start:" + Thread.currentThread().getName());
try {
Thread.sleep(5000L);
} catch (InterruptedException e) {
}
System.out.println("After ThreadB Sleep 5S");
synchronized (obj) {
obj.notify();
}
System.out.println("ThreadB notify:" + Thread.currentThread().getName());
}
}
}