package java1; class Account{//账户 private double balance;//余额 public Account(double balance) { this.balance = balance; } //存钱 //因为下面的两个顾客用的同一个acct,所以下面这个方法的锁this是唯一的。 public synchronized void deposit(double amt){ if(amt > 0){ balance += amt; System.out.println(Thread.currentThread().getName() + ":存钱成功。余额为:" + balance); } } } class Customer extends Thread{ private Account acct; public Customer(Account acct) { this.acct = acct;//目的是两个顾客用一个账户 } @Override public void run() { for (int i = 0; i < 3; i++) { acct.deposit(1000); } } } public class AccountTest { public static void main(String[] args) { Account acct = new Account(0);//一开始账户为0,没有钱 //两个顾客用一个账户 Customer c1 = new Customer(acct); Customer c2 = new Customer(acct); c1.setName("甲"); c2.setName("乙"); c1.start(); c2.start(); } }运行结果
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)