ReadWriteLock维护了一对锁,读锁可允许多个读线程并发使用,写锁是独占的。
下面通过一个简单的例子来了解ReadWriteLock。
1 package com.ccfdod.juc; 2 3 import java.util.concurrent.locks.ReadWriteLock; 4 import java.util.concurrent.locks.ReentrantReadWriteLock; 5 6 /** 7 * 写写/读写,需要互斥 8 * 读读,不需要互斥 9 */ 10 public class TestReadWriteLock { 11 12 public static void main(String[] args) { 13 ReadWriteLockDemo rw = new ReadWriteLockDemo(); 14 new Thread(new Runnable() { 15 16 @Override 17 public void run() { 18 rw.set((int) (Math.random() * 101)); 19 } 20 21 }, "Write:").start(); 22 23 for (int i = 0; i < 100; i++) { 24 new Thread(new Runnable() { 25 26 @Override 27 public void run() { 28 rw.get(); 29 } 30 31 }, "Read:").start(); 32 } 33 } 34 } 35 36 class ReadWriteLockDemo { 37 38 private int number = 0; 39 40 private ReadWriteLock lock = new ReentrantReadWriteLock(); 41 42 //读 43 public void get() { 44 lock.readLock().lock(); //上锁 45 try { 46 System.out.println(Thread.currentThread().getName() + " : " + number); 47 } finally { 48 lock.readLock().unlock(); //释放锁 49 } 50 } 51 52 //写 53 public void set(int number) { 54 lock.writeLock().lock(); //上锁 55 try { 56 System.out.println(Thread.currentThread().getName()); 57 this.number = number; 58 } finally { 59 lock.writeLock().unlock(); //释放锁 60 } 61 } 62 }