ReentrantLock 可重入锁: 线程进入后上锁,若同一线程进去可以再次进入
方法:
new ReentrantLock(true) ; // 加 true 后变为 公平锁
Lock lock = new ReentrantLock()
lock.lock() 上锁
lock.unlock() 解锁 ( ← 一定要写在 try finally 的 finally 中)
ReadWriteLock 读写锁:
共享锁
排他锁 (互斥锁)
import java.util.Random;
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 ReentrantReadWriteLockDemo {
static Lock lock = new ReentrantLock();
static ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
static Lock readLock = readWriteLock.readLock();
static Lock writeLock = readWriteLock.writeLock();
private static int value;
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 writeR = () -> write(lock, 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();
}
}