赞
踩
- public class UseReentrantReadWriteLock {
- private ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
- //原来读锁和写锁都是用ReentrantReadWriteLock创建出来的,哪个方法需要什么锁,就调用什么锁的lock()方法,不过最后记得要释放锁。
- private ReadLock rLock = rwLock.readLock();
- private WriteLock wLock = rwLock.writeLock();
-
- public void read(){ //读操作
- try{
- //因为这里模拟的是读操作,所以调用的是读锁的lock方法
- rLock.lock();
- System.out.println("线程:"+Thread.currentThread().getName()+"进入读操作");
- Thread.sleep(2000);
- }catch(Exception e){
- e.printStackTrace();
- }finally{
- System.out.println("线程:"+Thread.currentThread().getName()+"执行完读操作");
- rLock.unlock();
- }
- }
-
- public void write(){ //写操作
- try{
- //因为这里模拟的是写操作,所以调用的是写锁的lock方法。
- wLock.lock();
- System.out.println("线程:"+Thread.currentThread().getName()+"进入写操作");
- Thread.sleep(2000);
- }catch(Exception e){
- e.printStackTrace();
- }finally{
- System.out.println("线程:"+Thread.currentThread().getName()+"执行完写操作");
- wLock.unlock();
- }
- }
-
- public static void main(String[] args) {
- UseReentrantReadWriteLock urLock = new UseReentrantReadWriteLock();
- Thread t1 = new Thread(new Runnable(){
-
- @Override
- public void run() {
- urLock.read();
- }
-
- },"t1");
- Thread t2 = new Thread(new Runnable(){
-
- @Override
- public void run() {
- urLock.read();
- }
-
- },"t2");
-
- t1.start();
- t2.start();
- }
- }
- 线程:t2进入读操作
- 线程:t1进入读操作
- 线程:t2执行完读操作
- 线程:t1执行完读操作
- UseReentrantReadWriteLock urLock = new UseReentrantReadWriteLock();
- Thread t1 = new Thread(new Runnable(){
- @Override
- public void run() {
- urLock.write();
- }
-
- },"t1");
- Thread t2 = new Thread(new Runnable(){
-
- @Override
- public void run() {
- urLock.write();
- }
-
- },"t2");
-
- t1.start();
- t2.start();
- 线程:t2进入写操作
- 线程:t2执行完写操作
- 线程:t1进入写操作
- 线程:t1执行完写操作
- UseReentrantReadWriteLock urLock = new UseReentrantReadWriteLock();
- Thread t1 = new Thread(new Runnable(){
-
- @Override
- public void run() {
- urLock.read();
- }
-
- },"t1");
- Thread t2 = new Thread(new Runnable(){
-
- @Override
- public void run() {
- urLock.write();
- }
-
- },"t2");
-
- t1.start();
- t2.start();
- 线程:t2进入写操作
- 线程:t2执行完写操作
- 线程:t1进入读操作
- 线程:t1执行完读操作
读写锁还挺有意思的。。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。