ReentrantReadWriteLock:
类ReentrantLock具有相互互斥的排他效果,也就是说,同一时间,只有一个线程执行lock()方法后面的任务。这样做虽然可以解决问题,但是效率非常低。使用ReentrantReadWriterLock可以加快运行效率,某些不需要操作实例变量的方法中,完全可以使用它来提升代码运行效率。
为什么不需要操作实例变量变量方法才可以用它来提升效率呢?
- (1),读读不互斥
- (2),读写互斥
- (3),写读互斥
- (4),写写互斥
读读不互斥:
import java.util.concurrent.locks.ReentrantReadWriteLock; /** * @ClassName ReentrantReadWriteLockRRExample * @projectName: object1 * @author: Zhangmingda * @description: XXX * date: 2021/4/25. */ public class ReentrantReadWriteLockRRExample { public static void main(String[] args) { ReentrantReadWriteLock rWlock = new ReentrantReadWriteLock(); Runnable r = () ->{ rWlock.readLock().lock(); try { System.out.println("当前时间戳:" + System.currentTimeMillis()); Thread.sleep(1000); System.out.println("当前时间戳:" + System.currentTimeMillis()); } catch (InterruptedException e) { e.printStackTrace(); }finally { rWlock.readLock().unlock(); } }; Thread t1 = new Thread(r,"t1"); Thread t2 = new Thread(r,"t2"); t1.start(); t2.start(); } }
读写互斥:
import java.util.concurrent.locks.ReentrantReadWriteLock; /** * @ClassName ReentrantReadWriteLockRW * @projectName: object1 * @author: Zhangmingda * @description: XXX * date: 2021/4/25. */ public class ReentrantReadWriteLockRW { public static void main(String[] args) { ReentrantReadWriteLock rWLock = new ReentrantReadWriteLock(true); Runnable rr = () -> { String tName = Thread.currentThread().getName(); rWLock.readLock().lock(); System.out.println(tName + "开始读..."); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }finally { System.out.println(tName + "读完了!"); rWLock.readLock().unlock(); } }; Runnable rw = () -> { String tName = Thread.currentThread().getName(); rWLock.writeLock().lock(); System.out.println(tName + "开始写..."); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }finally { System.out.println(tName + "写完了!"); rWLock.writeLock().unlock(); } }; Thread reader = new Thread(rr,"读者1"); Thread reader1 = new Thread(rr,"读者2"); Thread writer = new Thread(rw,"作家1"); Thread writer1 = new Thread(rw,"作家2"); reader.start(); reader1.start(); writer.start(); writer1.start(); } }