多线程——银行取钱经典案例

实体类——银行

public class Account {
    //账户
    private String actno;
    //余额
    private double balance;

    private Object obj1 = new Object();

    public Account() {
    }

    public Account(String actno, double balance) {
        this.actno = actno;
        this.balance = balance;
    }

    public String getActno() {
        return actno;
    }

    public void setActno(String actno) {
        this.actno = actno;
    }

    public double getBalance() {
        return balance;
    }

    public void setBalance(double balance) {
        this.balance = balance;
    }

    public void withdraw(double money){

//        Object obj2 = new Object();
        synchronized(this) { //this指向当前对象Account,只同步需要共享的
//        synchronized("a") { //字符串在常量池中,是所有都共有的
//        synchronized(obj1) { //是this中的私有属性,作用和this一样
//        synchronized(obj2) { //是在方法内声明的,是局部变量,线程不安全
            //取款之前
            double before = this.getBalance();
            //取款之后
            double after = before - money;
            try {
                Thread.sleep(1000*1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //更新余额
            this.setBalance(after);
        }
    }
}

 线程类,继承Thread,重写run方法,在run方法里边对金额进行操作

public class AccountThread extends Thread{
    //两个线程共用一个账户对象
    private Account act;

    //通过构造方法传过来账户对象
    public AccountThread(Account act) {
        this.act = act;
    }

    @Override
    public void run() {
        //取款
        double money = 5000;
        act.withdraw(money);
        System.out.println(Thread.currentThread().getName() +"对账户"+act.getActno()+"取款成功,余额"+act.getBalance());
    }
}

 测试类,模拟三个人的取款操作,t1和t2是同一个账户,使用一个共享资源,t3是单独的一个账户,不是同一个共享资源可以进行并发,不会出现线程安全的问题

public class Test {
    public static void main(String[] args) {
        Account account = new Account("001", 10000);
        Thread t1 = new AccountThread(account);
        Thread t2 = new AccountThread(account);

        Account account2 = new Account("002", 10000);
        Thread t3 = new AccountThread(account2);

        t1.setName("t1");
        t2.setName("t2");
        t3.setName("t3");
        t1.start();
        t2.start();
        t3.start();
    }
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值