"读写" 、"写读"、"写写"都是同步的、互斥的
1、Service.java
package ReentrantReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; public class Service { private ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); //写写互斥 public void write(){ try{ try{ lock.writeLock().lock();//写锁 System.out.println("获得写锁"+Thread.currentThread().getName()+" "+System.currentTimeMillis()); Thread.sleep(10000); }finally{ lock.writeLock().unlock();//解锁 } }catch(Exception e){ e.printStackTrace(); } } }
可以发现,lock.writeLock()的效果就是同一时间只允许一个线程执行lock()方法后面的代码
2、ThreadA.java
package ReentrantReadWriteLock; public class ThreadA extends Thread{ private Service service ; public ThreadA(Service service){ super(); this.service = service; } @Override public void run(){ service.write(); } }
3、ThreadB.java
package ReentrantReadWriteLock; public class ThreadB extends Thread{ private Service service ; public ThreadB(Service service){ super(); this.service = service; } @Override public void run(){ service.write(); } }
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(); } }
可以自己更改ThreadA和ThreadB类中的run()方法里的read()、write()方法,实验"读写"、"写读"、"写写"