首页 新闻 搜索 专区 学院

ReentrantLock 枷锁之后,多线程操作一个数时,出现重复值

0
悬赏园豆:10 [待解决问题]

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SynchronizedThread {
    public void useThread() {
        Bank bank = new Bank();
        NewThread new_thread = new NewThread(bank);
        System.out.println("线程1");
        Thread thread1 = new Thread(new_thread);
        thread1.start();
        System.out.println("线程2");
        Thread thread2 = new Thread(new_thread);
        thread2.start();
    }

    public static void main(String[] args) {
        SynchronizedThread st = new SynchronizedThread();
        st.useThread();
    }
}

class Bank {
    private int account = 100;
    private Lock lock = new ReentrantLock();
    public int getAccount() {
        lock.lock();
        try{
            return account;
        }finally {
            lock.unlock();
        }
    }

    public void save(int money) {
        lock.lock();
        try {
            account += money;
        } finally {
            lock.unlock();
        }
    }
}

class NewThread implements Runnable {
    private Bank bank;

    public NewThread(Bank bank) {
        this.bank = bank;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            bank.save(10);
            System.out.println(i + "账户余额为:" +bank.getAccount());
        }
    }
}

========================下面是打印的结果==================
线程1
线程2
0账户余额为:120
0账户余额为:120

1账户余额为:140
2账户余额为:150
3账户余额为:160
4账户余额为:170
5账户余额为:180
6账户余额为:190
7账户余额为:200
8账户余额为:210
9账户余额为:220
1账户余额为:130
2账户余额为:230
3账户余额为:240
4账户余额为:250
5账户余额为:260
6账户余额为:270
7账户余额为:280
8账户余额为:290
9账户余额为:300

线程1和线程2的0账户重复了,请问这是怎么回事?

来着201780813的主页 来着201780813 | 初学一级 | 园豆:194
提问于:2019-03-11 17:14
< >
分享
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册