wait
1.wait,notify,notifyAll是Object类的方法。在使用时必须包含在synchronized方法中或者同步块中。即必须先获得正确的对象锁,调用wait后,会释放自己占有的锁并且加入到等待池中等待。直到有其他线程调用同一个对象的notify/notifyAll方法才会唤醒。如果在没有获得对象锁之前调用wait,notify,notifyAll会抛出IllegalMonitorStateException异常。
2.wait(long timeout)和wait(long timeout, int nanos)可以设置一个最长等待时间,如果超过这个时间,那么就不在等待,timeout的单位是毫秒,nanos的单位是纳秒。但是wait(0)和wait(0,0)相当于wait()
3.唤醒条件:
- notify:其他线程调用notify时,将从等待池中随机选择一个等待线程唤醒。
- notifyAll:其他线程调用notifyAll会唤醒等待池中的所有线程。
- Interrupt:wait执行前或者执行中,线程发生中断,此时会抛出InterruptedException异常。
- 虚假唤醒:等待的线程可能会莫名其妙被唤醒(尽管发生的概率很小),所以API文档中推荐的写法是使用while而不是if。这样如果发生虚假唤醒,会再次进入等待状态。
synchronized (obj) {
while (<condition does not hold>)
obj.wait(timeout);
... // Perform action appropriate to condition
}
notify
线程在调用notify之后,会随机从等待池中选择一个等待线程唤醒,但是是在当前执行的同步块或者同步方法调用结束之后才会释放对象锁,等待的线程只有获得对象锁之后才能继续执行。而其他没有被唤醒的线程会继续等待。他们等待的是notify/notifyAll
notifyAll
线程调用notifyAll之后会唤醒等待池中全部线程,但是由于只能有一个线程获得对象锁,所有其他线程还得等待,但是这时他们等待的是对象锁。
例子:
1.实现生产者消费者问题
public class Wait {
public static void main(String[] args){
Queue<Integer> queue = new LinkedList<Integer>();
Thread thread1 = new Thread(new Producter(queue));
Thread thread2 = new Thread(new Consumer(queue));
thread2.start();
thread1.start();
}
}
class Consumer implements Runnable {
private Queue<Integer> queue;
public Consumer(Queue<Integer> queue){
this.queue = queue;
}
private void get() throws InterruptedException{
synchronized(queue){
while(queue.size() <= 0)
queue.wait();
System.out.println("consumer get:" + queue.poll());
queue.notify();
}
}
@Override
public void run(){
for(int i = 0; i < 5; i++){
try {
get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class Producter implements Runnable{
private Queue<Integer> queue;
Random rand = new Random();
public Producter(Queue<Integer> queue){
this.queue = queue;
}
private void put() throws InterruptedException{
int a = rand.nextInt(100);
synchronized(queue){
while(queue.size() >= 1)
queue.wait();
queue.offer(a);
System.out.println("producter put" + a);
queue.notify();
}
}
@Override
public void run(){
for(int i = 0; i < 5; i++){
try {
put();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
notify信号丢失
上面生产者消费者代码能够正确执行,消费者进入wait之前,生产者发送的notify会丢失,但是不会产生问题。因为此时队列的长度是大于0的。但是假设等待条件是很任性的或者必须要他等待,然后之后再唤醒它,那么这样的话等待的线程会一直等待下去。
join和yield
join是等待线程结束后才能继续执行。
yield是让出当前线程。让出线程后线程调度会随机选一个就绪的线程,所以让出的线程可能会继续执行。
总结
在多线程通讯中,使用valatile可以实现共享内存的通信,但是会有忙等待。使用wait和notify可以消除忙等待但是会有notify信号丢失的情况。最好应该使用信号量。