代码如下
- class Account {
- int money = 100;
- public int getMoney() {
- return money;
- }
- public void add(int m) {
- money += m;
- }
- public void desc(int m) {
- money -= m;
- }
- }
- //存钱
- class Deposit implements Runnable {
- private Account account;
- private int money;
- public Deposit(Account account, int money) {
- this.account = account;
- this.money = money;
- }
- @Override
- public void run() {
- synchronized (Account.class) {
- System.out.print(“当前余额:” + account.getMoney() + ” 存入:” + money);
- account.add(money);
- System.out.println(“,成功,余额为” + account.getMoney());
- }
- }
- }
- //取钱
- class Withdraw implements Runnable {
- private Account account;
- private int money;
- public Withdraw(Account account, int money) {
- this.account = account;
- this.money = money;
- }
- @Override
- public void run() {
- synchronized (Account.class) {
- System.out.print(“当前余额:” + account.getMoney() + ” 取出:” + money);
- if (account.getMoney() >= money) {
- account.desc(money);
- System.out.println(“,成功,余额为” + account.getMoney());
- } else {
- System.out.println(“,失败,余额不足”);
- }
- }
- }
- }
- public class Demo8 {
- public static void main(String args[]) throws InterruptedException {
- Account account = new Account();
- Thread t1 = new Thread(new Deposit(account, 100));
- Thread t2 = new Thread(new Withdraw(account, 200));
- Thread t3 = new Thread(new Deposit(account, 300));
- Thread t4 = new Thread(new Withdraw(account, 400));
- t1.start();
- t2.start();
- t3.start();
- t4.start();
- }
- }
运行结果图
注意这里的锁必须是唯一的,不能用 this,因为 this 的话指的是当前对象,这个两个不同类的线程对象,必须用一致的锁,比如都用 synchronized (“”) ,或者用某个类当做锁。