ReentrantReadWriteLock
ReentrantReadWriteLock
:读写锁,在执行读操作时可以异步执行。读-读异步,读-写异步,写-写异步。
ReentrantLock
是完全互斥排他的,效率低;
ReentrantReadWriteLock
有两个锁:
读相关的锁:共享锁
写相关的锁:排他锁
package ReentranyReadWriteLock; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantReadWriteLock; //ReentrantReadWriteLock:读读共享、读写互斥 public class Read_Write { public static void main(String[] args) { Service service = new Service(); for(int i=0;i<5;i++){ new MyThread1(service).start(); new MyThread2(service).start(); } } } class Service{ private ReentrantReadWriteLock lock=new ReentrantReadWriteLock(); //读操作 public void read(){ try { lock.readLock().lock(); System.out.println("线程:"+Thread.currentThread().getName() +"读......"+System.currentTimeMillis()); Thread.sleep(500); System.out.println(" 线程:"+Thread.currentThread().getName() +"读......结束"+System.currentTimeMillis()); } catch (Exception e) { e.printStackTrace(); } finally { lock.readLock().unlock(); } } public void write(){ try { lock.writeLock().lock(); System.out.println("线程:"+Thread.currentThread().getName()+"写>>>>>>> " +System.currentTimeMillis()); Thread.sleep(500); System.out.println(" 线程:"+Thread.currentThread().getName()+"写>>>>>>>结束 " +System.currentTimeMillis()); } catch (Exception e) { e.printStackTrace(); } finally { lock.writeLock().unlock(); } } } class MyThread1 extends Thread{ private Service service; public MyThread1(Service service){ this.service=service; } @Override public void run() { service.read(); } } class MyThread2 extends Thread{ private Service service; public MyThread2(Service service){ this.service=service; } @Override public void run() { service.write(); } } /* 线程:Thread-0读......1609738706403 线程:Thread-2读......1609738706403 线程:Thread-0读......结束1609738706918 线程:Thread-2读......结束1609738706918 线程:Thread-3写>>>>>>> 1609738706918 线程:Thread-3写>>>>>>>结束 1609738707434 线程:Thread-1写>>>>>>> 1609738707434 线程:Thread-1写>>>>>>>结束 1609738707949 线程:Thread-5写>>>>>>> 1609738707949 线程:Thread-5写>>>>>>>结束 1609738708465 线程:Thread-4读......1609738708465 线程:Thread-6读......1609738708465 线程:Thread-6读......结束1609738708981 线程:Thread-4读......结束1609738708981 线程:Thread-7写>>>>>>> 1609738708981 线程:Thread-7写>>>>>>>结束 1609738709481 线程:Thread-8读......1609738709481 线程:Thread-8读......结束1609738709996 线程:Thread-9写>>>>>>> 1609738709996 线程:Thread-9写>>>>>>>结束 1609738710512 */