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;
		}
	}
}

猜你喜欢

转载自1609919154.iteye.com/blog/2391537