锁定等于/通知的优点是什么?

时间:2012-03-29 13:48:58

标签: java concurrency

锁定等于/通知的优势是什么? 代码非常相似。

    private Object full = new Object();
private Object empty = new Object();

private Object data = null;

public static void main(String[] args) {
    Test test = new Test();
    new Thread(test.new Producer()).start();
    new Thread(test.new Consumer()).start();
}

public void push(Object d) {
    synchronized (full) {
        while (data != null)
            try {
                full.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    }
    data = d;
    System.out.println("push");
    synchronized (empty) {
        if (data != null)
            empty.notify();
    }
}

public Object pop() {
    synchronized (empty) {
        while (data == null)
            try {
                empty.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    }
    Object o = data;
    data = null;
    System.out.println("pop");
    synchronized (full) {
        if (data == null)
            full.notify();
    }
    return o;
}

class Producer implements Runnable {
    public void run() {
        while (true) {
            push(new Object());
        }
    }
}

class Consumer implements Runnable {
    public void run() {
        while (true) {
            pop();
        }
    }
}

    private final ReentrantLock lock = new ReentrantLock();
private final Condition fullState = lock.newCondition();
private final Condition emptyState = lock.newCondition();

private Object data = null;

public static void main(String[] args) {
    Test test = new Test();
    new Thread(test.new Producer()).start();
    new Thread(test.new Consumer()).start();
}

public void push(Object d) {
    lock.lock();
    try {
        while (data != null)
            try {
                fullState.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        data = d;
        System.out.println("push");
        emptyState.signal();
    } finally {
        lock.unlock();
    }
}

public Object pop() {
    Object result;
    lock.lock();
    try {
        while (data == null)
            try {
                emptyState.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        result = data;
        data = null;
        System.out.println("pop");
        fullState.signal();
    } finally {
        lock.unlock();
    }
    return result;
}

class Producer implements Runnable {
    public void run() {
        while (true) {
            push(new Object());
        }
    }
}

class Consumer implements Runnable {
    public void run() {
        while (true) {
            pop();
        }
    }
}

1 个答案:

答案 0 :(得分:4)

查看ReDntratLock的JavaDoc,您的问题将得到解答。

“可重入互斥锁具有与使用同步方法和语句访问的隐式监视器锁相同的基本行为和语义,但具有扩展功能。”

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/locks/ReentrantLock.html