为什么使用Lock没有解决线程安全问题

/**
 * 银行有一个账户。
 * 有两个储户分别向同一个账户存3000元,每次存1000,存3次。每次存完打印账户余额。
 *
 */
public class AccountTest {
    public static void main(String[] args) {

        //账户(锁)只有一个
        Account account = new Account(0);

        //拥有同一个账户的两个客户(线程)
        Customer c1 = new Customer(account);
        Customer c2 = new Customer(account);

        Thread t1 = new Thread(c1);
        Thread t2 = new Thread(c2);

        t1.setName("丈夫");
        t2.setName("妻子");

        t1.start();
        t2.start();
    }
}


class Account{

    private double balance;

    public Account() {
    }

    public Account(double balance) {
        this.balance = balance;
    }

    //功能:存钱
//    public synchronized void deposit(double money)
    public void deposit(double money){
        //为什么这里使用Lock锁效果不一样???
        ReentrantLock rl = new ReentrantLock();

        rl.lock();
        try {
            if (money>0){
                balance+=money;

                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                System.out.println(Thread.currentThread().getName()+"存钱成功,余额为"+balance);

            }
        } finally {
            rl.unlock();
        }
    }

}

class Customer implements Runnable{

    private Account acc;

    public Customer() {
    }

    public Customer(Account acc) {
        this.acc = acc;
    }

    @Override
    public void run() {
          //往里面存3次1000块
          for (int i = 0; i < 3; i++) {
              acc.deposit(1000);
          }
    }
}
阅读 1.1k
1 个回答

每次调用都重新 new 一个 Lock 出来,于是都是不同的 lock ,达不到互斥的效果。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题