应用示例
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