class Accout implements Runnable{
private int accout=0;
private ReentrantLock lock=new ReentrantLock();
public void run(){
try{
lock.lock();
for(int i=0;i<3;i++){
accout=accout+1000;
System.out.println(Thread.currentThread().getName()+"存入了1000,当前余额为:"+accout);
}
}finally {
lock.unlock();
}
}
}
public class BankExercise {
public static void main(String[] args) {
Accout p=new Accout();
Thread a=new Thread(p);
Thread b=new Thread(p);
a.setName("a");
b.setName("b");
a.start();
b.start();
}
}
手动锁住和解锁