WriteLock ReadLock
读写锁:分为读锁和写锁,多个读锁不互斥,读锁与写锁互斥,这是由jvm自己控制的,你只要上好相应的锁即可。如果你的代码只读数据,可以很多人同时读,但不能同时写,那就上读锁;如果你的代码修改数据,只能有一个人在写,且不能同时读取,那就上写锁。总之,读的时候上读锁,写的时候上写锁!
ReentrantReadWriteLock会使用两把锁来解决问题,一个读锁,一个写锁
线程进入读锁的前提条件:没有其他线程的写锁
package cn.itcast.lesson12; import java.io.ObjectOutputStream.PutField; import java.util.Random; import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.omg.CORBA.PUBLIC_MEMBER; public class ReadWriteLockTest { public static void main(String[] args) { final Queue3 q3 = new Queue3(); for (int i=0; i < 3; i++) { new Thread() { public void run() { while (true) { q3.get(); } } }.start(); new Thread() { public void run() { while (true) { //传入一个data值 q3.put(new Random().nextInt(10000)); } } }.start(); } } } class Queue3{ private Object data = null;//共享數據,只能有一个线程能写该数据,但有多个线程能读该数据 private ReentrantReadWriteLock rw1 = new ReentrantReadWriteLock(); public void get(){ rw1.readLock().lock(); System.out.println(Thread.currentThread().getName()+" be ready to read data!"); try{ Thread.sleep((long) (Math.random()*1000)); }catch (Exception e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"have read data: " + data); rw1.readLock().unlock(); } public void put(Object data){ rw1.writeLock().lock(); System.out.println(Thread.currentThread().getName()+" be ready to write data!"); try{ Thread.sleep((long) (Math.random()*1000)); }catch (Exception e) { e.printStackTrace(); } this.data = data; System.out.println(Thread.currentThread().getName()+"have write data: "+ data); rw1.writeLock().unlock(); } }
打印
Thread-0 be ready to read data! Thread-2 be ready to read data! Thread-0have read data: null Thread-2have read data: null Thread-1 be ready to write data! Thread-1have write data: 8157 Thread-3 be ready to write data! Thread-3have write data: 5388 Thread-3 be ready to write data! Thread-3have write data: 3672 Thread-3 be ready to write data! Thread-3have write data: 5668 Thread-3 be ready to write data! Thread-3have write data: 3150 Thread-3 be ready to write data! Thread-3have write data: 4848 Thread-3 be ready to write data! Thread-3have write data: 8036 Thread-3 be ready to write data! Thread-3have write data: 3333 Thread-3 be ready to write data! Thread-3have write data: 5873 Thread-3 be ready to write data! Thread-3have write data: 5840 Thread-3 be ready to write data!