使用两个线程竞争读锁,一个线程竞争写锁。看读写锁的获取率。
代码如下
public class ThreadDuXieSuo {
public static ReadWriteLocklock =new ReentrantReadWriteLock();
public static LockreadLock =lock.readLock();
public static LockwriteLock =lock.writeLock();
public static void main(String[] args) {
ExecutorService service = Executors.newFixedThreadPool(3);
service.execute(new Task(readLock,"读锁"));
service.execute(new Task(readLock,"读锁"));
service.execute(new Task(writeLock,"写锁"));
}
}
class Taskimplements Runnable {
private Locklock;
private Stringparam;
public Task(Lock lock, String param) {
this.lock = lock;
this.param = param;
}
@Override
public void run() {
while (true) {
try {
lock.lock();
System.out.println(Thread.currentThread().getId() +"获得了" +param);
Thread.sleep(1000);
}catch (Exception e) {
System.out.println(Thread.currentThread().getId()+"线程被中断");
}finally {
System.out.println(Thread.currentThread().getId() +"释放了" +param);
lock.unlock();
}
}
}
}
运行结果
读写锁竞争时,写锁的优先级高。如果有这种频繁竞争的情况可能会出现读锁一直处于等待状态。
解决方案
可以考虑使用公平锁,不过公平锁吞吐量没有非公平锁高。
new ReentrantReadWriteLock(true);返回一个公平锁。