jmu-java-07 multithreading-mutually exclusive access

Topic details:

6-2 jmu-Java-07 Multithreading - Mutually Exclusive Access (10 points)

Define Accountclass
attributes:
private int balance
method:
getter method
void deposit(int money) //Save money, add money
void withdraw(int money) to the balance //Withdraw money, subtract money from the balance

Note: There may be multiple threads accessing the balance property of the Account object at the same time through the depositor method.withdraw

Referee test procedure:

import java.util.Scanner;

/*你的代码,即Account类的代码*/

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

Answer code:

class Account{
	private int balance=0;

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

	public Account() {
		super();
	}

	public int getBalance() {
		return balance;
	}

	public void setBalance(int balance) {
		this.balance = balance;
	}
	public synchronized void deposit(int money) {
		this.balance = balance+money;
	}
	public synchronized void withdraw(int money) {
		this.balance = balance-money;
	}
}

Guess you like

Origin blog.csdn.net/qq_54587141/article/details/120997864