package abit;
public class RemoveMoney implements Runnable{
public static int mymoney=2000;
public static void main(String[] args){
RemoveMoney t=new RemoveMoney();
new Thread(t,"A").start();
new Thread(t,"B").start();
}
public void run() {
try{
Thread.sleep(1000);
}catch(Exception e){}
remove(1500);
}
public synchronized void remove(int money){
if(mymoney>money){
mymoney-=money;
System.out.println(Thread.currentThread().getName()+"取走"+money+",剩下"+mymoney);
}else{
System.out.println(Thread.currentThread().getName()+"你的余额不足");
}
}
}
/*输出:
A取走1500,剩下500
B你的余额不足
*/
可以去除synchronized试试,会导致:
A取走1500,剩下500
B取走1500,剩下500