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(); } } }