ReadWriteLock read/write lock, readwritelock read/write
ReadWriteLock maintains a pair of locks. Read locks can be used by multiple read threads concurrently, and write locks are exclusive.
The following is a simple example to learn about ReadWriteLock.
1 package com. ccfdod. juc; 2 3 import java. util. concurrent. locks. readWriteLock; 4 import java. util. concurrent. locks. reentrantReadWriteLock; 5 6/** 7 * write/read/write, mutually exclusive 8 * read, mutex 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 @ Override17 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 @ Override27 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 // read 43 public void get () {44 lock. readLock (). lock (); // lock 45 try {46 System. out. println (Thread. currentThread (). getName () + ":" + number); 47} finally {48 lock. readLock (). unlock (); // release lock 49} 50} 51 52 // write 53 public void set (int number) {54 lock. writeLock (). lock (); // lock 55 try {56 System. out. println (Thread. currentThread (). getName (); 57 this. number = number; 58} finally {59 lock. writeLock (). unlock (); // release lock 60} 61} 62}