如果在引用上调用,wait()是否等待引用的对象或引用本身?

时间:2018-05-24 01:14:51

标签: java multithreading wait notify

在这种情况下,是否会通知线程1(在等待引用而不是对象本身时)?

static Object lock=new Object();
//Thread 1:
Object reference=lock;
reference.wait();

//Thread 2:
lock.notify();

1 个答案:

答案 0 :(得分:1)

由于在对象上获得了锁,因此等待引用或该引用所指向的对象是相同的。无论有多少引用,如果它们指向内存中的相同对象wait(),notify(),notifyall()将无缝地工作。看看下面的代码。

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;

public class ProducerConsumer {

private Queue<Integer>      queue   = new ArrayBlockingQueue<>(10);
private LinkedList<Integer> list    = new LinkedList<>();
int                         limit   = 10;

public static void main(String[] args) {

    final ProducerConsumer pc = new ProducerConsumer();
    final ProducerConsumer pcRef = pc;

    Thread producer = new Thread(new Runnable() {
        int i = 1;

        @Override
        public void run() {
            while (true) {
                synchronized (pcRef) {
                    while (pc.limit == pc.list.size()) {
                        try {
                            pcRef.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    pc.list.add(i);
                    System.out.println("Producer @work : " + pc.list.size());
                    pcRef.notify();
                }

            }
        }
    });

    Thread consumer = new Thread(new Runnable() {

        @Override
        public void run() {
            while (true) {
                synchronized (pc) {
                    while (0 == pc.list.size()) {
                        try {
                            pc.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    int val = pc.list.removeFirst();
                    System.out.println("Consumer @work : " + pc.list.size() + " : " + val);
                    pc.notify();
                }

            }
        }
    });

    producer.start();
    consumer.start();

    try {
        producer.join();
        consumer.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

}

}

注释以下行,您将看到消费者线程正在等待通知。

pc.list.add(i);
System.out.println("Producer @work : " + pc.list.size());
//pcRef.notify();