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; } } }
上一篇: 网络化服务之战 云计算与物联网紧密结合
下一篇: JS 操作 Cookie