6-3 jmu-Java-07多线程-同步访问

现已有Account类,拥有
属性:
private int balance
方法:
相应的getter方法。

要求为该类编写:
void deposit(int money) //存钱,在余额的基础上加上money
void withdraw(int money) //取钱,在余额的基础上减去money

注意:

  1. 取钱时如果balance<0的时候,会抛出异常。在多线程情况下,如只有一个存钱的线程,但是有多个取钱的线程,很可能会抛出异常。
  2. 需要编写完整的deposit方法与withdraw的前半部分代码解决该问题。

裁判测试程序:

import java.util.Scanner;

//这里是已有的Account类前半部分的代码
/*这里是deposit代码*/
/*这里是withdraw代码的前半部分*/
    if(balance<0) //这里是withdraw代码的后半部分。
        throw new IllegalStateException(balance+"");    
    }

/*系统已有代码,无需关注*/

输入样例:

分别为初始余额、存钱次数、存钱金额
取钱次数、取钱金额。有3个线程。

0 100000 12
100000 4

输出样例:

余额:使用线程跑出的结果。
余额:存钱次数*存钱金额 - 取钱次数*取钱金额*3

0
0

代码:

package com.PTA;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        Account account = new Account(0);
        Thread t1 = new Thread(new Draw(account));
        Thread t2 = new Thread(new Draw(account));
        Thread t3 = new Thread(new Draw(account));
        Thread t4 = new Thread(new deposit(account));
        t4.start();
        t1.start();
        t2.start();
        t3.start();
        t1.join();
        t2.join();
        t3.join();
        t4.join();
        System.out.println(account.getBalance());
    }
}

class deposit implements Runnable {
    private final Account account;

    deposit(Account account) {
        this.account = account;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100000; i++) {
            account.deposit(12);
        }
    }
}

class Draw implements Runnable {
    private final Account account;

    public Draw(Account account) {
        this.account = account;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100000; i++) {
            account.withdraw(4);
        }
    }
}

class Account {
    private int balance;

    public Account(int balance) {
        this.balance = balance;
    }

    public int getBalance() {
        return balance;
    }

    public synchronized void deposit(int money) {
        this.balance += money;
        if (this.balance >= 0)
            this.notifyAll();
    }

    public synchronized void withdraw(int money) {
        while (this.balance < money) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        if (this.balance < 0) {
            throw new IllegalStateException(balance + "");
        }
        this.balance -= money;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值