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账户重复了,请问这是怎么回事?