使用多线程对一个属性进行操作

public class Account implements Runnable {
    private int money=1000;//定义一个int类型的变量,

    public int getMoney() {
        return money;
    }

    public void setMoney(int money) {
        this.money = money;
    }

    public void run() {//重写run方法
        while (true){
            if(money<=0){
                System.out.println("余额不足以支付 "+Thread.currentThread().getName()+" 的取款,余额为"+money);
                return;
            }else {//Thread.currentThread().getName()表示获取的线程的名字
                money=money-200;//进行修改属性。
                System.out.println(Thread.currentThread().getName()+"准备取款\n"+Thread.currentThread().getName()+" 取款完成");

            }
        }
    }
}

public class AccountTest {//两个线程同时对一个属性进行操作。
    public static void main(String[] args) {
        Account account = new Account();
        new Thread(account,"张三").start();//“张三是这个线程的名字”
        new Thread(account,"张三的妻子").start();//同理,“张三的妻子也是这个线程的名字”
    }
}

猜你喜欢

转载自blog.csdn.net/gadxiong/article/details/80327402
今日推荐