关于ReentrantReadWriteLock中ReadLock的作用



 class Data {
    ReadWriteLock lock = new ReentrantReadWriteLock();
    Lock readLock = lock.readLock();
    Lock writeLock = lock.writeLock();
    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");

    public void get() {
        readLock.lock();
        System.out.println(Thread.currentThread().getName() + " Get Begin " + getTime());
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println(Thread.currentThread().getName() + " Get End " + getTime());
            readLock.unlock();
        }
    }

    public String getTime() {
        return sdf.format(new Date());
    }
}


 public class MyRunnable implements Runnable {
    Data data;

    public MyRunnable(Data data) {
        this.data = data;
    }

    @Override
    public void run() {
        data.get();
    }
}


 public class Client {
    public static void main(String[] args) {
        Data data = new Data();
        MyRunnable one = new MyRunnable(data);
        MyRunnable two = new MyRunnable(data);
        Thread first = new Thread(one, "One");
        Thread second = new Thread(two, "Two");
        first.start();
        second.start();
    }
}

输出结果:


 One Set Begin 00:28:27
One Set End 00:28:32
Two Set Begin 00:28:32
Two Set End 00:28:37

从结果可知,加了ReadLock允许多线程对Data进行访问,这样的话ReadLock的作用体现在哪里呢?难道我在加了ReadLock的代码块里硬是要修改数据不可以吗?这样的话每个线程既获得了执行权,又修改了数据,岂不是不对了么?

思路僵住了,望前辈赐教:)

java 并发

chenxu 9 years ago

Your Answer