JAVA JUC 读写锁

 

 

 

应用示例

class Demo{
    int number;
    ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    public void read(){
        //读锁
        lock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+" read "+number);
        } finally {
            lock.readLock().unlock();
        }

    }
    public void write(){
        lock.writeLock().lock();
        try {
            number++;
            System.out.println(Thread.currentThread().getName()+"add number");
        } finally {
            lock.writeLock().unlock();
        }
    }

}
public class writeReadLockTest {
    public static void main(String[] args) {
        Demo d = new Demo();
        for(int i =0;i<20;i++)
            new Thread(new Runnable() {
                @Override
                public void run() {
                    d.write();
                }
            },"writeThread "+i+" ").start();
        for(int i =0;i<20;i++)
            new Thread(new Runnable() {
                @Override
                public void run() {
                    d.read();
                }
            },"redaThread "+i+" ").start();

    }
}
View Code

 

posted @ 2020-03-13 17:50  超级学渣渣  阅读(157)  评论(0编辑  收藏  举报