欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Lock的使用 Lock锁 

程序员文章站 2022-05-28 12:46:34
...
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;
		}
	}
}

 

相关标签: Lock锁