ReentranReadWriteLock读写锁,内部维护了二个锁,一个用于读操作支持多线程并发执行,一个用于写操作只能单线程执行。在多线程的场景下,如果对资源加了写锁,其它线程无法再获取写锁和读锁;如果对资源加了读锁,其它线程可以继续加读锁,也就是说可以多线程同时读的操作。在实际应用中,读多写少的情况下,能够提供更好的并发性和吞吐量。
功能:
- 支持公平和非公平获取锁的方式
- 可重入、可中断
示例:
package com.test.thread;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class TestReadWriteLock {
static ReadWriteLock lock = new ReentrantReadWriteLock();
public static void main(String[] args) {
ExecutorService exe = Executors.newFixedThreadPool(50);
for (int i = 0; i < 2; i++) {
exe.execute(new Runnable() {
@Override
public void run() {
try {
writer(Thread.currentThread());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
for (int i = 0; i < 5; i++) {
exe.execute(new Runnable() {
@Override
public void run() {
try {
read(Thread.currentThread());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
exe.shutdown();
}
public static void writer(Thread thread) throws InterruptedException {
lock.writeLock().lock();
try {
for (int i = 0; i < 5; i++) {
Thread.sleep(new Random().nextInt(1100));
System.out.println("=写====>" + thread.getName());
}
} finally {
System.out.println("==写====释放锁===>" + thread.getName());
lock.writeLock().unlock();
}
}
public static void read(Thread thread) throws InterruptedException {
lock.readLock().lock();
try {
for (int i = 0; i < 5; i++) {
Thread.sleep(new Random().nextInt(1100));
System.out.println("=读====>" + thread.getName());
}
} finally {
System.out.println("==读====释放锁===>" + thread.getName());
lock.readLock().unlock();
}
}
}