1 public class ReadWriteLockTest { 2 private static Lock loc = new ReentrantLock(); 3 4 5 private static ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock(); 6 private static Lock readLock = readWriteLock.readLock(); 7 private static Lock writeLock = readWriteLock.writeLock(); 8 9 private int value; 10 11 public Object handleRead(Lock lock) throws InterruptedException { 12 try { 13 lock.lock(); 14 Thread.sleep(1000); 15 return value; 16 } finally { 17 lock.unlock(); 18 } 19 } 20 21 public void handleWrite(Lock lock, int value) throws InterruptedException { 22 try { 23 lock.lock(); 24 Thread.sleep(1000); 25 this.value = value; 26 } finally { 27 lock.unlock(); 28 } 29 } 30 31 public static void main(String[] args) { 32 final ReadWriteLockTest test = new ReadWriteLockTest(); 33 Runnable readRun = () -> { 34 try { 35 // test.handleRead(readLock); 36 test.handleRead(loc); 37 } catch (InterruptedException e) { 38 e.printStackTrace(); 39 } 40 }; 41 42 Runnable writeRun = () -> { 43 try { 44 // test.handleWrite(writeLock, new Random().nextInt()); 45 test.handleWrite(loc, new Random().nextInt()); 46 } catch (InterruptedException e) { 47 e.printStackTrace(); 48 } 49 }; 50 52 53 for (int i = 0; i < 18; i++) { 54 new Thread(readRun).start(); 55 } 56 57 for (int i = 18; i < 20; i++) { 58 59 new Thread(writeRun).start(); 60 } 61 63 } 64 65 66 }
在读操作比较多的时候,读写分离锁很明显能提高性能
时间: 2024-10-12 11:13:31