多个线程可以同时读,读读是异步的、非互斥的
1、Service.java(封装的方法,供线程A和B访问)
package ReentrantReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; public class Service { private ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); public void read(){ try{ try{ lock.readLock().lock();//读锁 System.out.println("获得读锁"+Thread.currentThread().getName()+" "+System.currentTimeMillis()); Thread.sleep(10000);//验证A和B是否同时读进来 }finally{ lock.readLock().unlock();//解锁 } }catch(Exception e){ e.printStackTrace(); } } }
2、ThreadA.java(线程A)
package ReentrantReadWriteLock; public class ThreadA extends Thread{ private Service service ; public ThreadA(Service service){ super(); this.service = service; } @Override public void run(){ service.read(); } }
3、ThreadB.java(线程B)
package ReentrantReadWriteLock; public class ThreadB extends Thread{ private Service service ; public ThreadB(Service service){ super(); this.service = service; } @Override public void run(){ service.read(); } }
4、Run.java(运行类)
package ReentrantReadWriteLock; public class Run { public static void main(String[] args) { Service service = new Service(); ThreadA a = new ThreadA(service); a.setName("A"); ThreadB b = new ThreadB(service); b.setName("B"); a.start(); b.start(); } }