JAVA线程锁,除Lock的传统锁,又有两种特殊锁,叫读写锁ReadWriteLock
其中多个读锁不互斥,读锁和写锁互斥,写锁和写锁互斥
例子:
/** * java线程锁分为读写锁 ReadWriteLock 其中多个读锁不互斥,读锁和写锁互斥,写锁和写锁互斥 * * @author * * * */ public class ReadWriteLockTest { public static void main(String[] args) { final Operation operation = new Operation(); for (int i = 1; i <= 3; i++) { new Thread(new Runnable() { @Override public void run() { operation.getData(); } }).start(); new Thread(new Runnable() { @Override public void run() { operation.putData(new Random().nextInt(1000)); } }).start(); } } } class Operation{ private ReadWriteLock rwl = new ReentrantReadWriteLock(); //读写锁 private int data; public void getData(){ rwl.readLock().lock(); try { System.out.println(Thread.currentThread().getName()+" be readly get data "); Thread.sleep(1000); System.out.println(Thread.currentThread().getName()+" have data value :" + data); } catch (InterruptedException e) { e.printStackTrace(); }finally{ rwl.readLock().unlock(); } } public void putData(int data){ rwl.writeLock().lock(); try { System.out.println(Thread.currentThread().getName()+" be readly write data"); Thread.sleep(1000); this.data = data; System.out.println(Thread.currentThread().getName() + " have write data value : "+ data); } catch (InterruptedException e) { e.printStackTrace(); }finally{ rwl.writeLock().unlock(); } } }