package com.yjc.juc; import java.util.concurrent.locks.ReentrantLock; class ZiYuan { ReentrantLock reentrantLock = new ReentrantLock(); public void method1() { reentrantLock.lock(); try { System.out.println("进入方法1"); System.out.println("准备调用方法2"); method2(); } catch (Exception e) { e.printStackTrace(); } finally { reentrantLock.unlock(); } } public void method2() { reentrantLock.lock(); try { System.out.println("进入方法2"); } catch (Exception e) { e.printStackTrace(); } finally { reentrantLock.unlock(); } } } public class MyLock { public static void main(String[] args) { ZiYuan ziYuan=new ZiYuan(); ziYuan.method1(); } }
package com.yjc.juc; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; public class MyReadWriteLock{ public static void main(String[] args){ ReadWriteLockDemo rwd = new ReadWriteLockDemo(); //启动100个读线程 for (int i = 0; i < 100; i++) { new Thread(new Runnable() { @Override public void run() { rwd.get(); } }).start(); } //写线程 new Thread(new Runnable() { @Override public void run() { rwd.set((int)(Math.random()*101)); } },"Write").start(); } } class ReadWriteLockDemo{ //模拟共享资源--Number private int number = 0; // 实际实现类--ReentrantReadWriteLock,默认非公平模式 private ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); //读 public void get(){ //使用读锁 readWriteLock.readLock().lock(); try { System.out.println(Thread.currentThread().getName()+" : "+number); }finally { readWriteLock.readLock().unlock(); } } //写 public void set(int number){ readWriteLock.writeLock().lock(); try { this.number = number; System.out.println(Thread.currentThread().getName()+" : "+number); }finally { readWriteLock.writeLock().unlock(); } } }
原文:https://www.cnblogs.com/yjc1605961523/p/12566301.html