Lock版的生产者消费者问题

HeJin大约 1 分钟JavaJUC并发编程

官方文档

image-20210311131300769
image-20210311131300769

synchronized与Lock等待和唤醒方法对比

image-20210311131211730
image-20210311131211730
public interface Condition
    
Condition factors out the Object monitor methods (wait, notify and notifyAll) into distinct objects to give the effect of having multiple wait-sets per object, by combining them with the use of arbitrary Lock implementations. Where a Lock replaces the use of synchronized methods and statements, a Condition replaces the use of the Object monitor methods.
/**
 * 资源类
 * 判断等待、业务、通知
 */
class Data2{
    private int num = 0;

    /**
     * condition.await(); 等待
     * condition.signalAll(); 唤醒
     */
    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    public void increment() throws InterruptedException {
        lock.lock();
        try {
            // 业务代码
            while (num != 0){
                // 等待
                condition.await();
            }
            num++;
            System.out.println(Thread.currentThread().getName()+"==>"+num);
            // 通知其他线程 +1完毕
            condition.signalAll();
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void decrement() throws InterruptedException {
        lock.lock();
        try {
            // 业务代码
            while (num == 0){
                // 等待
                condition.await();
            }
            num--;
            System.out.println(Thread.currentThread().getName()+"==>"+num);
            // 通知其他线程 -1完毕
            condition.signalAll();
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

测试结果一样。

A==>1
B==>0
A==>1
B==>0
C==>1
B==>0
C==>1
B==>0
C==>1
D==>0
A==>1
B==>0
C==>1
D==>0
A==>1
B==>0
C==>1
D==>0
A==>1
B==>0
C==>1
D==>0
A==>1
B==>0
C==>1
D==>0
A==>1
B==>0
C==>1
D==>0
A==>1
B==>0
C==>1
D==>0
A==>1
D==>0
A==>1
D==>0
C==>1
D==>0

Process finished with exit code 0

任何一个新的技术,绝对不仅仅只是覆盖了原来的技术,优势和补充。

Condition 精准通知和唤醒线程