`
落叶换新叶
  • 浏览: 24369 次
  • 性别: Icon_minigender_1
社区版块
存档分类
最新评论

Lock的使用

阅读更多
public class LockTest {

	public static void main(String[] args) {
	
		LockTest test = new LockTest();
		final DealMoney money = test.new DealMoney();
		
		for(int i=0;i<10;i++) {			
			new Thread(new Runnable() {
				@Override
				public void run() {
					money.getM();
				}
			}).start();
		}
		for(int i=0;i<10;i++) {			
			new Thread(new Runnable() {
				@Override
				public void run() {
					money.setM(20);
				}
			}).start();
		}
	}
	
	public class DealMoney {
		private int money = 100;
		
		private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
		
		public DealMoney() {
		}
		public void setM(int money) {
			lock.writeLock().lock();
			try {
				System.out.println(Thread.currentThread().getName()+":进入写操作");
				try {
					Thread.sleep(10000);
				} catch (InterruptedException e) {
				}
				this.money = this.money+money;
				System.out.println(Thread.currentThread().getName()+":存入金额:"+this.money);
			} finally {
				lock.writeLock().unlock();
			}
		}
		public int getM() {
			lock.readLock().lock();
			System.out.println(Thread.currentThread().getName()+":进入读操作");
			try {
				Thread.sleep(10000);
				System.out.println(Thread.currentThread().getName()+":得到金额:"+this.money);
			} catch (InterruptedException e) {
			}finally {
				lock.readLock().unlock();
			}
			return this.money;
		}
	}
}

 

0
0
分享到:
评论
1 楼 masuweng 2017-08-30  
   没注释;

相关推荐

Global site tag (gtag.js) - Google Analytics