为什么我测试的不会发生money为负数的情况呢?public class TestBank { public static void main(String[] args) {
TestBank tb = new TestBank();
Bank bank = new Bank("djb", 1000);
for (int i = 0; i < 100; i++) {
tb.new ThreadTestBank(bank).start();
}
} public class ThreadTestBank extends Thread {
Bank banks; public ThreadTestBank(Bank bank) {
banks = bank;
} public void run() {
while (!Thread.interrupted()) { boolean ok = banks.withdraw(1000);
try {
Thread.sleep(1000);
} catch (InterruptedException e) { e.printStackTrace();
}
if (ok) {
banks.deposit(1000);
}
}
}
}
}public class Bank {
private int money;
private String name;
public Bank(String name,int money)
{
this.money=money;
this.name=name;
}
public void deposit(int m)
{
money+=m;
}
public boolean withdraw(int m)
{
System.out.println("current money:"+money);
if(money>=m){
money-=m;
check();
return true;
}else
{
return false;
}
}
private void check()
{
if(money<0)
{
System.out.println(this.name+"'s money is fushu!"+money);System.exit(-1);
}
}
}
TestBank tb = new TestBank();
Bank bank = new Bank("djb", 1000);
for (int i = 0; i < 100; i++) {
tb.new ThreadTestBank(bank).start();
}
} public class ThreadTestBank extends Thread {
Bank banks; public ThreadTestBank(Bank bank) {
banks = bank;
} public void run() {
while (!Thread.interrupted()) { boolean ok = banks.withdraw(1000);
try {
Thread.sleep(1000);
} catch (InterruptedException e) { e.printStackTrace();
}
if (ok) {
banks.deposit(1000);
}
}
}
}
}public class Bank {
private int money;
private String name;
public Bank(String name,int money)
{
this.money=money;
this.name=name;
}
public void deposit(int m)
{
money+=m;
}
public boolean withdraw(int m)
{
System.out.println("current money:"+money);
if(money>=m){
money-=m;
check();
return true;
}else
{
return false;
}
}
private void check()
{
if(money<0)
{
System.out.println(this.name+"'s money is fushu!"+money);System.exit(-1);
}
}
}
money-=m;
check();
return true;
}
------------------------------------
只要m>0
money 永远都是>=0怎么可能会有负数呢?
代码错误!
到线程1走过这个条件后
if(money>=m){
money是大于0,但如果此时线程2将这个money减成负数你说可能不?