基本代码中显示了读/写锁定与同步之间的区别

时间:2019-01-19 14:03:50

标签: java multithreading locks

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

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();
        }
    }
}

1 个答案:

答案 0 :(得分:2)

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

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

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

在这里阅读以查看如何检查线程是否已结束,以便您可以测量执行时间: How to know if other threads have finished?


编辑以回答评论: 嘿,我的回答有点简化了(好吧,因为多线程很难),所以我现在可以将您与其他资源链接起来,以提供更深入的了解。 / p>

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

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;
    }
}