读写锁ReentrantReadWriteLock概述
读写锁ReentrantReadWriteLock,使用它比ReentrantLock效率更高。
读写锁表示两个锁,一个是读操作相关的锁,称为共享锁;另一个是写操作相关的锁,称为排他锁。
1、读和读之间不互斥,因为读操作不会有线程安全问题
2、写和写之间互斥,避免一个写操作影响另外一个写操作,引发线程安全问题
3、读和写之间互斥,避免读操作的时候写操作修改了内容,引发线程安全问题
多个Thread可以同时进行读取操作,但是同一时刻只允许一个Thread进行写入操作。
读操作和读操作共享
请看例子
ThreadDomain44类和main方法
public class ThreadDomain44 extends ReentrantReadWriteLock
{
public void read()
{
try
{
readLock().lock();
System.out.println(Thread.currentThread().getName() + "获得了读锁, 时间为" +
System.currentTimeMillis());
Thread.sleep(10000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
finally
{
readLock().unlock();
}
}
public static void main(String[] args)
{
final ThreadDomain44 td = new ThreadDomain44();
Runnable readRunnable = new Runnable()
{
public void run()
{
td.read();
}
};
Thread t0 = new Thread(readRunnable);
Thread t1 = new Thread(readRunnable);
t0.start();
t1.start();
}
}
输出结果如下
Thread-0获得了读锁, 时间为1564018325618
Thread-1获得了读锁, 时间为1564018325618
尽管加了Thread.sleep(10000);两个线程几乎同时执行lock()后面的方法。说明readLock().lock()允许多个线程执行并且能提高执行效率。
写操作和写操作互斥
请看例子
public class ThreadDomain45 extends ReentrantReadWriteLock {
public void write()
{
try
{
writeLock().lock();
System.out.println(Thread.currentThread().getName() + "获得了写锁, 时间为" +
new Date());
Thread.sleep(10000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
finally
{
writeLock().unlock();
}
}
public static void main(String[] args)
{
final ThreadDomain45 td = new ThreadDomain45();
Runnable readRunnable = new Runnable()
{
public void run()
{
td.write();
}
};
Thread t0 = new Thread(readRunnable);
Thread t1 = new Thread(readRunnable);
t0.start();
t1.start();
}
}
输出结果
Thread-1获得了写锁, 时间为Tue Jul 30 11:26:21 CST 2019
Thread-0获得了写锁, 时间为Tue Jul 30 11:26:31 CST 2019
可以看到,后获得锁的Thread-0等待了十秒,说明写和写互斥
读操作和写操作互斥/写操作和读操作互斥
例子如下
public class ThreadDomain46 extends ReentrantReadWriteLock {
public void write()
{
try
{
writeLock().lock();
System.out.println(Thread.currentThread().getName() + "获得了写锁, 时间为" +
new Date());
Thread.sleep(10000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
finally
{
writeLock().unlock();
}
}
public void read()
{
try
{
readLock().lock();
System.out.println(Thread.currentThread().getName() + "获得了读锁, 时间为" +
new Date());
Thread.sleep(10000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
finally
{
readLock().unlock();
}
}
public static void main(String[] args)
{
final ThreadDomain46 td = new ThreadDomain46();
Runnable readRunnable = new Runnable()
{
public void run()
{
td.read();
}
};
Runnable writeRunnable = new Runnable()
{
public void run()
{
td.write();
}
};
Thread t0 = new Thread(readRunnable);
Thread t1 = new Thread(writeRunnable);
t0.start();
t1.start();
}
}
输出结果如下
Thread-0获得了读锁, 时间为Tue Jul 30 11:49:15 CST 2019
Thread-1获得了写锁, 时间为Tue Jul 30 11:49:26 CST 2019
可以看到Thread-0获得读锁执行完10s后Thread-1才获得了写锁,说明读操作和写操作互斥。
另一种输出结果如下
Thread-1获得了写锁, 时间为Tue Jul 30 14:14:07 CST 2019
Thread-0获得了读锁, 时间为Tue Jul 30 14:14:17 CST 2019
可以看到Thread-1获得写锁执行完10s后Thread-0才获得了读锁,说明写操作和读操作互斥。