read/write 锁与基本代码中显示的同步之间的区别

The difference between read/write locks vs synchronized shown on basic code

在我的作业中,我需要在代码中展示 read/write 锁和 'synchronized' 关键字用法之间的区别。我真的不知道该怎么做,也不知道理解这种差异的明确方法是什么。我还需要显示以两种方式执行同一任务之间的时间差。这是我试过的代码(虽然没有同步)

public class Main {

    public static void main(String[] args) {

        Number number = new Number(5);

        Thread t1 = new Thread(){
            public void run(){
                System.out.println(number.getData());
                number.changaData(10);
                System.out.println(number.getData());
            }};
            Thread t2 = new Thread(){
                public void run(){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    System.out.println(number.getData());
                    number.changaData(20);
                    System.out.println(number.getData());
                }};

                t2.start();
                t1.start();
    }
}


public class Number {

    private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
    private final Lock readLock = rwl.readLock();
    private final Lock writeLock = rwl.writeLock();
    int value;

    public Number(int value) {
        this.value = value;
    }

    public int getData() {
        readLock.lock();
        try {
            return value;
        }
        finally {
            readLock.unlock();
        }
    }

    public int changaData(int change) {
        writeLock.lock();
        try {
            value = change;
            return value;
        }
        finally {
            writeLock.unlock();
        }
    }
}

synchronized 和 read/write 锁之间的区别在于,当您使用 synchronized 时,它一次只允许一个线程访问。使用 read/write 锁,您可以同时拥有多个读取器(假设没有写锁),因此在某些情况下您可以获得更好的并发性能,尤其是在此处有很多读取时。

您应该添加更多访问此对象的线程以测试性能。

您可以简单地计算操作完成和开始之间的时间来衡量性能(例如 - Long startTime = System.nanoTime();)。

阅读此处了解如何检查线程是否已结束以便测量执行时间: How to know if other threads have finished?


编辑以回答评论: 嘿,我的回答有点简化(好吧,非常简单,因为多线程很难),因为我是在做这些事情的间隙写这篇文章的,所以,现在,我可以 link 给你一些其他资源,这些资源提供更多 -深度观察。

根据您现有的非常简单的示例 class:

class Number {

    private int value;

    public Number(int value) {
        this.value = value;
    }

    public synchronized int getValue() {
        return value;
    }

    public synchronized int changeData(int change) {
        value = change;
        return value;
    }
}