- 就是共享锁和排他锁(读锁和写锁)
- 有的是读线程,有的是写线程
- 简单上锁时,效率特别低
- 上的是读锁的时候,其他线程可以读,但是不可以写;上的是写锁的时候,其他线程不可以读也不可以写
- 这里的锁与数据库里的不会冲突,是两回事;数据库的锁是数据库中的锁,从数据库中读出来到程序中,程序是在内存中的;到内存中了之后,数据库就已经读完了
- 不会出现得不到锁,除非cpu只挑读或者写的运行
- 与ReentrantLock的Condition很类似
- 互斥锁=排他锁
- 读的时候不加锁会出现读的时候可以往里面写,会造成数据不一致(脏读)
package com.mashibing.juc.c_020;
import java.util.Random;
import java.util.concurrent.atomic.LongAdder;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class T10_TestReadWriteLock {
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!");
//模拟写操作
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
//Runnable readR = ()-> read(lock);
Runnable readR = ()-> read(readLock);
//Runnable writeR = ()->write(lock, new Random().nextInt());
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();
}
}