12. ReadWriteLock 读写锁
package com.gf.demo11; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * 1. ReadWriteLock : 读写锁 * * 写写/读写 互斥 * 读读 不互斥 * */ public class TestReadWriteLock { public static void main(String[] args) { ReadWriteLockDemo rw = new ReadWriteLockDemo(); new Thread(new Runnable() { @Override public void run() { rw.set((int)(Math.random()*101)); } },"Write").start(); for (int i = 0; i < 10; i++) { new Thread(new Runnable() { @Override public void run() { rw.get(); } }).start(); } } } class ReadWriteLockDemo{ private int number = 0; private ReadWriteLock lock = new ReentrantReadWriteLock(); //读 public void get(){ lock.readLock().lock(); //上锁 try { System.out.println(Thread.currentThread().getName() +" : " + number); } finally { lock.readLock().unlock();//释放锁 } } //写 public void set(int number){ lock.writeLock().lock(); try { System.out.println(Thread.currentThread().getName() +" : " + number); this.number = number; } finally { lock.writeLock().unlock(); } } }
关注我的公众号,精彩内容不能错过
作者:程序员果果
出处:blog.itwolfed.com
欢迎关注公众号——《程序员果果》 ,分享SpringBoot、SpringCloud、Dubbo、Golang、Docker相关知识与技巧。
原创 Java 博客,点我看看?