Like ReadWriteLock Lock is an interface that provides the operating mechanism readLock and writeLock other kinds of locks, one for read-only lock is a write lock
Mutually exclusive principles:
Read - can coexist,
Read - write can not coexist,
Write - write can not coexist.
package com.wf.zhang.juc; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * ReadWritelock Read-Write Lock * * * Write / read-write needs "exclusive" * * Do not need to read exclusive */ public class TestReadWriterlock { public static void main(String[] args) { RW ReadWriterlockDemo = new new ReadWriterlockDemo (); // a thread write new new the Thread ( new new the Runnable () { @Override public void run() { rw.set((int) (Math.random() * 101)); } },"写锁").start(); @ 100 threads read for ( int I = 0; I <= 100; I ++ ) { new Thread(new Runnable() { @Override public void run() { rw.get(); } }).start(); } } } class ReadWriterlockDemo { private int number = 0; private ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); //读 public void get() { readWriteLock.readLock().lock(); try { System.out.println(Thread.currentThread().getName() + " 读" + number); } finally { readWriteLock.readLock().unlock(); } } //写 public void set(int number) { this.number = number; readWriteLock.writeLock().lock(); try { System.out.println(Thread.currentThread().getName() + " 写 " +number); } finally { readWriteLock.writeLock().unlock(); } } }