Lock锁与synchronized锁的区别

Lock锁与synchronized锁的区别

1、synchronized锁是可以帮助我们自动开锁和关闭锁
2、Lock锁,我们最常用的是ReentrantLock重入锁,需要我们手动的开锁和手动关锁
3、synchronized只能与wait()、notify()方法一起使用
4、ReentrantLock只能与Condition类中的await()、single()方法一起使用

用ReentranLock修改我们上篇文章的生产者和消费者模型

、产品
Lock锁与synchronized锁的区别
、生产者

/**
 * 生产者
 */
class Product extends Thread {
    private int count = 1;
    private User user;

    public Product(User user) {
        this.user = user;
    }

    @Override
    public void run() {
        while (true) {
            try {
                //开锁
                user.getLock().lock();
                if (user.flag) {
                    try {
                        user.getCondition().await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                if (count == 1) {
                    user.setId(1);
                    user.setName("紫炎易霄");
                    user.setAge(21);
                } else {
                    user.setId(6);
                    user.setName("黑袍萧寻");
                    user.setAge(66);
                }
                count = (count + 1) % 2;
                user.flag = true;
                //唤醒另一个线程
                user.getCondition().signal();
            } catch (Exception e) {
                e.getStackTrace();
            } finally {
                //释放锁
                user.getLock().unlock();
            }

        }
    }
}

、消费者

/**
 * 消费者
 */
class Consumer extends Thread {
    private User user;

    public Consumer(User user) {
        this.user = user;
    }

    @Override
    public void run() {
        while (true) {
            try {
                user.getLock().lock();
                //上锁
                if (!user.flag) {
                    try {
                        user.getCondition().await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(user);
                user.flag = false;
                //唤醒生产者线程
                user.getCondition().signal();
            } catch (Exception e) {
                e.getStackTrace();
            } finally {
                //释放锁
                user.getLock().unlock();
            }
        }
    }
}

、运行结果
Lock锁与synchronized锁的区别