Java--银行账户存取款线程设计1(交互线程)

线程之间可能无关,也可能交互。
而线程的同步机制并发执行的交互线程间存在与时间有关的错误。

public class account {

    private String name;
    private double balance;
    public account(String name) {
        this.name = name;
        this.balance=0;
    }
    public String getName() {
        return name;
    }
    public double getBalance() {
        return balance;
    }
    //
    public void put(double value){
        if(value>0){
            this.balance=this.balance+value;
        }

    }
    public double  get(double value){
        if(value>0){
            if(value<=balance){
                this.balance=this.balance-value;
            }else{
                value=this.balance;
                this.balance=0;
            }

        }
        return value;
    }
}
public class save extends Thread{
    private account a;
    private double value;

    public save(account a, double value) {
        this.a = a;
        this.value = value;
    }

    public void run() {
        double b=a.getBalance();
        a.put(value);
        System.out.println(a.getName()+"账户,现有"+b+",存入"
        +value+",余额"+a.getBalance());
    }


}
public class fetch extends Thread{
    private account a;
    private double value;

    public fetch(account a, double value) {
        this.a = a;
        this.value = value;
    }

    public void run() {
        double b=a.getBalance();
        System.out.println(a.getName()+"账户,现有"+b+",取出"
        +a.get(value)+",余额"+a.getBalance());
    }
}
public class bank {

    public static void main(String[] args) {

// account a1=new account("wang");
// save s1=new save(a1,100);
// save s1=new save(new account("wang"),100);
// s1.start();
        account a1=new account("wang");
        new save(a1,100).start();
        new save(a1,200).start();
        new fetch(a1,300).start();

        new save(new account("xu"),100).start();
    }

}

运行结果1:
wang账户,现有0.0,存入100.0,余额100.0
wang账户,现有100.0,取出100.0,余额0.0
wang账户,现有0.0,存入200.0,余额200.0
xu账户,现有0.0,存入100.0,余额100.0
运行结果2:
wang账户,现有0.0,存入100.0,余额100.0
wang账户,现有100.0,存入200.0,余额300.0
xu账户,现有0.0,存入100.0,余额100.0
wang账户,现有300.0,取出300.0,余额0.0
由运行结果可以看出,线程很乱

你可能感兴趣的:(线程)