这是一个双线程的银行取款问题
public class Account
/*
银行类
*/
{
private int balance = 600;//余额
public void withBalance(int money) //取款方法
{
this.balance = this.balance - money;
}
public int getBalance()//返回余额
{
return balance;
}
}
public class AccountRunnable implements Runnable { /*
取款线程
*/
private Account account = new Account();//创建一个银行类的对象
@Override
public void run()
{
if (account.getBalance() > 400)
{
account.withBalance(400);//取款400
System.out.println(Thread.currentThread().getName()+"取款成功"+"当前余额为"+account.getBalance());
// 输出当前线程的名字 和 钱款剩余
}
else
{
System.out.println(Thread.currentThread().getName()+"余额不足"+"当前余额为"+account.getBalance());
// 输出当前线程的名字 和 钱款剩余
}
}
}
main 方法:
public class TestAccount {
public static void main(String[] args) {
// 创建两个线程,模拟两个用户
Runnable runnable = new AccountRunnable();
Thread thread1 = new Thread(runnable, "张三");
Thread thread = new Thread(runnable, "张三的妻子");
/*thread1.setName("hun");
thread.setName("wi");*/
// 启动两个线程,模拟两个用户取款
thread1.start();
thread.start();
}
}
当thread1.start(); 方法在thread.start();方法之上时 遇到了问题 只有张三可以取款成功 如图:
而thread.start 方法在 thread1.start(); 之上时 却运行正常 如图: