1. 程式人生 > >ReadWriteLock讀寫鎖

ReadWriteLock讀寫鎖

ReadWriteLock管理的是一組鎖,一個是讀鎖,一個是寫鎖。

當前兩個鎖是同時使用的。

其實很多人能理解寫鎖,因為寫鎖的話,寫如果併發的話,那就出現髒資料。

不過為什麼會存在讀鎖?讀為什麼要鎖?

其實資料有完整性。

比如:

public class Man {


    public String name = "0";
    public String age = "18";


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }
}
public class MutilThread {
    private static Man man = new Man();
    public static ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    private static Lock writeLock = lock.writeLock();
    private static Lock readLock = lock.readLock();
    public static void main(String[] args)   {
        ExecutorService service = Executors.newFixedThreadPool(20);
        service.execute(new Runnable() {
            @Override
            public void run() {
                read();
            }
        });
        for (int i = 0; i < 30; i++) {
            service.execute(new Runnable() {
                @Override
                public void run() {
                    write();
                }
            });
        }
    }

    public static  void read(){
        while (true){
            readLock.lock();
            Thread thread = Thread.currentThread();
            System.out.println("thread name "+thread.getName()+",man name  = " + man.name+"  age : "+ man.age);
            if (man.name.equals( "餘")&&man.age.equals("22")){
                            System.out.println("1+thread name "+thread.getName()+",man name  = " + man.name+"  age : "+ man.age);
            }
            if (man.name.equals( "小明")&&man.age.equals("18")){
                System.out.println("2+thread name "+thread.getName()+",man name  = " + man.name+"  age : "+ man.age);
            }
            readLock.unlock();
        }
    }
    public static void write() {
        while (true) {
            writeLock.lock();
            Thread thread = Thread.currentThread();
            if (thread.getId()%2!=0){
                man.name = "餘";
                man.age = "18";
//                System.out.println("thread name "+thread.getName()+",man name  = " + man.name+"  age : "+ man.age);
            }
            if (thread.getId()%2!=1){
                man.name = "小明";
                man.age = "22";
//                System.out.println("thread name "+thread.getName()+",man name  = " + man.name+"  age : "+ man.age);
            }
            writeLock.unlock();
        }
    }
}

 

存在兩個成員變數,如果我們讀的時候,如果只是寫加了鎖,讀沒有加讀鎖的話,你會發現讀的時候沒有讀完整,會出現讀的髒資料。比如出現餘 22歲的這個情況是不應該出現的。所以讀鎖是保證讀取的資料的完整性的。