public class Demo {
public static void main(String[] args) {
final Account acc = new Account();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
acc.getMoney(10000);
}
System.out.println("取钱结束!");
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
acc.setMoney(10000);
}
System.out.println("存钱结束!");
}
}).start();
try {
Thread.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("余额:" + acc.getBananace());
}
}
class Account {
private int bananace = 1500000;
public synchronized void setMoney(int i) {
this.bananace += i;
}
public synchronized void getMoney(int i) {
this.bananace -= i;
}
public int getBananace() {
return this.bananace;
}
} |
|