java读写锁ReadWriteLock

Posted fliay

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java读写锁ReadWriteLock相关的知识,希望对你有一定的参考价值。

package com.java.concurrent;

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

public class TestReadWriteLock {

    public static void main(String[] args) {
        final ReadWriteLockDemo rw2 = new ReadWriteLockDemo();
        new Thread(new Runnable() {
            
            public void run() {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                rw2.set(20);
                
            }
        },"Write:").start();

        
        new Thread(new Runnable() {
            
            public void run() {
                while(true)
                rw2.get();
            }
        },"Read").start();
        
    }


}

class ReadWriteLockDemo {
    private int number = 0;
    // 定义一个读写锁
    private ReadWriteLock lock = new ReentrantReadWriteLock();

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

    // 写数据
    public void set(int number) {
        //创建写锁
        lock.writeLock().lock();
        try{
        System.out.println(Thread.currentThread().getName()+":"+number);

        this.number = number;
        }finally{
            lock.writeLock().unlock();
        }
    }

}

 

以上是关于java读写锁ReadWriteLock的主要内容,如果未能解决你的问题,请参考以下文章

java多线程 -- ReadWriteLock 读写锁

Java——多线程高并发系列之ReadWriteLock读写锁

Java——多线程高并发系列之ReadWriteLock读写锁

java读写锁ReadWriteLock

java多线程---读写锁ReadWriteLock

Java 读写锁 ReadWriteLock 原理与应用场景详解