java声明银行账户类锁_java中显式加锁---银行存取钱业务

1.[代码][Java]代码

package com.cn.chapter22;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.locks.Condition;

import java.util.concurrent.locks.Lock;

import java.util.concurrent.locks.ReentrantLock;

public class TestThread {

public static void main(String[] args) {

// TODO Auto-generated method stub

ExecutorService executors = Executors.newFixedThreadPool(2);

executors.execute(new DepositAPeenyTask());

executors.execute(new WithDraw());

executors.shutdown();

}

}

//存储类

class DepositAPeenyTask implements Runnable{

Account account1 = new Account();

public void run(){

try {

while(true){

account1.deposit((int)(Math.random()*500)+1);

Thread.sleep(1000);

}

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

//取钱类

class WithDraw implements Runnable {

Account account2 = new Account();

@Override

public void run() {

try {

while(true) {

account2.withDraw((int) (Math.random() * 1000) + 1);

Thread.sleep(1000);

}

} catch (Exception e) {

System.out.println(e.toString());

}

}

}

//账户类

class Account {

private static Lock lock = new ReentrantLock();

private static Condition condition = lock.newCondition();

private static int balance = 0 ;

//get the balance

public int getBalance(){

return balance;

}

//deposit the money

public void deposit(int amount){

lock.lock();

System.out.println("存入 "+amount+" 钱");

balance += amount;

System.out.println("账户共有资金:"+getBalance());

condition.signalAll();

lock.unlock();

}

//withDraw the money

public void withDraw(int amount){

int i = 0 ;

int j = 0 ;

lock.lock();

try{

System.out.println("i的值:"+(++i));

while(balance < amount){

System.out.println("你的取款金额为"+amount+"元,但是系统金额不足,请等待!");

condition.await();

System.out.println("j的值:"+(++j));

}

balance -= amount;

System.out.println("您已经取出"+amount+"元,您账户剩余的金额为:"+getBalance());

}catch (Exception e) {

System.out.println(e.toString());

}finally{

lock.unlock();

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值