Java多线程银行存取款程序

来源:互联网 发布:人工智能主题的基金 编辑:程序博客网 时间:2024/05/16 18:17
package com.rr.synchonized;


public class Account{

public Account(String n ,float a){
holderName = n;
amount = a;
}

public synchronized void deposit(float a){
amount +=a;
}

public synchronized void withdraw(float a){
if(a <= amount){
System.out.println("取出"+a+"元");
amount -= a;
}else{
System.out.println("余额不足");
}
}

public float checkBank(){
return amount;
}


String holderName;
float amount;

public static void main(String args[]){
Account ac = new Account("Li",300);
TestAccount1 ta = new TestAccount1(ac);
//TestAccount2 tb = new TestAccount2(ac);
Thread d1 = new Thread(ta);
Thread d2 = new Thread(ta);
d1.start();
d2.start();
}
}


class TestAccount1 implements Runnable{
public TestAccount1(Account ac){
this.account1 = ac;
}
public void run(){
account1.withdraw(200);
System.out.println("余额为"+account1.checkBank());
}

private Account account1; 
}


class TestAccount2 implements Runnable{
public TestAccount2(Account ac){
this.account2 = ac;
}
public void run(){
account2.deposit(200);
System.out.println("余额为"+account2.checkBank());
}

private Account account2; 

}



若无synchronized关键字,那么运行结果为:

取出200.0元
余额为100.0
取出200.0元
余额为-100.0

0 0
原创粉丝点击