ReentrantReadWriteLock共享锁排他锁
static class ReentrantWriteReadDemo{ //共享锁 排他锁 ReentrantReadWriteLock readWriteLock; //共享锁,所有线程可同时获得 并发量高。比如在线文档查看 ReentrantReadWriteLock.ReadLock readlock; //排他锁 同一时刻只有一个线程有权修改资源。比如在线文档编辑 ReentrantReadWriteLock.WriteLock writeLock; public ReentrantWriteReadDemo() { readWriteLock = new ReentrantReadWriteLock(); readlock = readWriteLock.readLock(); writeLock = readWriteLock.writeLock(); } public void read(){ String name = Thread.currentThread().getName(); try{ readlock.lock(); System.out.println(name+"正在读..."); Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } finally { readlock.unlock(); System.out.println(name+"读完了..."); } }public void write(){ String name = Thread.currentThread().getName(); try{ writeLock.lock(); System.out.println(name+"正在写入..."); Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } finally { writeLock.unlock(); System.out.println(name+"写入完毕..."); } } }
Dana.Lee
To:Dana_Lee1016@126.com