码迷,mamicode.com
首页 > 编程语言 > 详细

Java-ReentrantReadWriteLock的简单例子

时间:2015-07-07 22:49:41      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:

内容:读锁时共享的,写锁时互斥的(可见运行结果),都是通过AQS实现的。

public class ReentrantReadWriteLockTest {
	
	static class MyObject {
		private Object object;
		private ReadWriteLock lock = new ReentrantReadWriteLock();
		
		public void get() {
			lock.readLock().lock();
			System.out.println(Thread.currentThread().getName() + "准备读数据!!");
			
			try {
				Thread.sleep(new Random().nextInt(1000));
				System.out.println(Thread.currentThread().getName() + "读数据为:" + this.object);
			} catch (InterruptedException e) {
				e.printStackTrace();
			} finally {
				lock.readLock().unlock();
			}
		}
		
		public void put(Object object) {
			lock.writeLock().lock();
			System.out.println(Thread.currentThread().getName() + "准备写数据");
			
			try {
				Thread.sleep(new Random().nextInt(1000));
				this.object = object;
				System.out.println(Thread.currentThread().getName() + "写数据为" + this.object);
			} catch (InterruptedException e) {
				e.printStackTrace();
			} finally {
				lock.writeLock().unlock();
			}
		}
	}
	
	public static void main(String[] args) throws InterruptedException {
		final MyObject myObject = new MyObject();
		ExecutorService executor = Executors.newCachedThreadPool();
		
		for (int i = 0; i < 3; i++) {
			executor.execute(new Runnable() {
				
				@Override
				public void run() {
					for (int j = 0; j < 5; j++)
						myObject.put(new Random().nextInt(1000));
				}
			});
		}
		
		for (int i = 0; i < 3; i++) {
			executor.execute(new Runnable() {
				
				@Override
				public void run() {
					for (int j = 0; j < 5; j++)
						myObject.get();
				}
			});
		}
		
		executor.shutdown();
	}

}


运行结果:

技术分享

版权声明:本文为博主原创文章,未经博主允许不得转载。

Java-ReentrantReadWriteLock的简单例子

标签:

原文地址:http://blog.csdn.net/u011345136/article/details/46793981

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!