ReentrantReadWriteLock(读写锁)
读 共享锁
写 排它锁
ReadLock可以被多个线程持有并且在作用时排斥任何的WriteLock,而WriteLock则是完全的互斥
对于高读取频率而相对较低写入的数据结构,使用此类锁同步机制则可以提高并发量。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| public class ReadWriteLockDemo { static Lock lock = new ReentrantLock(); private static int value;
static ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); static Lock readLock = readWriteLock.readLock(); static Lock writeLock = readWriteLock.writeLock();
public static void read(Lock lock) { try { lock.lock(); Thread.sleep(1000); System.out.println("read over!"); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } }
public static void write(Lock lock, int v) { try { lock.lock(); Thread.sleep(1000); value = v; System.out.println("write over! " + value); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } }
public static void main(String[] args) {
Runnable readR = () -> read(readLock); Runnable writeR = () -> write(writeLock, new Random().nextInt());
for (int i = 0; i < 18; i++) new Thread(readR).start(); for (int i = 0; i < 2; i++) new Thread(writeR).start(); } }
|
在main方法中有一段代码注释,可以解开,然后将另外两句代码注释掉,对比一下执行,就会很明显的看到执行效率