7.ReadWriteLock的使用以及源码解读
作者:互联网
1.读读共享
public static void main(String[] args) { ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); for (int i = 0; i < 5; i++) { new Thread(()->{ Lock lock = readWriteLock.readLock(); try { lock.lock(); System.out.println(Thread.currentThread().getName()+"读数据"); TimeUnit.SECONDS.sleep(3); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } }).start(); } }
2.写写互斥
public static void main(String[] args) { ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); for (int i = 0; i < 5; i++) { new Thread(()->{ Lock lock = readWriteLock.writeLock(); try { lock.lock(); System.out.println(Thread.currentThread().getName()+"写数据"); TimeUnit.SECONDS.sleep(3); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } }).start(); } }
3.读写互斥,写读互斥就先不演示了。
public static void main(String[] args) { ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); new Thread(()->{ Lock lock = readWriteLock.readLock(); try { lock.lock(); System.out.println(Thread.currentThread().getName()+"0秒开始读数据,需要读5秒"); TimeUnit.SECONDS.sleep(5); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); System.out.println(Thread.currentThread().getName()+"读完毕,释放读锁"); } }).start(); new Thread(()->{ Lock lock = readWriteLock.writeLock(); try { TimeUnit.SECONDS.sleep(3); lock.lock(); System.out.println(Thread.currentThread().getName()+"3秒后开始开始写数据,瞬间写完"); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); System.out.println(Thread.currentThread().getName()+"写完毕,释放读锁"); } }).start(); }
标签:currentThread,Thread,ReadWriteLock,readWriteLock,System,解读,源码,lock,new 来源: https://www.cnblogs.com/johnzhao/p/15025985.html