读读不互斥:
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(); } }