其他分享
首页 > 其他分享> > JUC-10-ReadWriteLock读写锁

JUC-10-ReadWriteLock读写锁

作者:互联网

ReadWriteLock同Lock一样也是一个接口,提供了readLock和writeLock两种锁的操作机制,一个是只读的锁,一个是写锁              互斥原则: 读-读能共存, 读-写不能共存, 写-写不能共存。        
package com.wf.zhang.juc;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * ReadWritelock  读写锁
 *
 *
 * 写写/读写 需要"互斥"
 *
 * 读读 不需要互斥
 */
public class TestReadWriterlock {

    public static void main(String[] args) {
        ReadWriterlockDemo rw = new ReadWriterlockDemo();
        //一个线程写
        new Thread(new Runnable() {
            @Override
            public void run() {
                rw.set((int) (Math.random() * 101));
            }
        },"写锁").start();


        //100个线程读
        for (int i = 0; i <=100; i++) {

            new Thread(new Runnable() {
                @Override
                public void run() {
                    rw.get();
                }
            }).start();
        }

    }
}

class ReadWriterlockDemo {

    private int number = 0;

    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    //读
    public void get() {
        readWriteLock.readLock().lock();
        try {

            System.out.println(Thread.currentThread().getName() + " 读" + number);
        } finally {
            readWriteLock.readLock().unlock();
        }
    }

    //写
    public void set(int number) {
        this.number = number;
        readWriteLock.writeLock().lock();
        try {

            System.out.println(Thread.currentThread().getName() + " 写 " +number);
        } finally {
            readWriteLock.writeLock().unlock();
        }
    }
}

 

标签:JUC,10,ReadWriteLock,读写,互斥,共存,new,public
来源: https://www.cnblogs.com/wf-zhang/p/12080612.html