我们不仅可以使用synchronized来实现多线程同步,还可以通过创建锁对象来实现多线程的同步,还是上次模拟取现的操作,这次利用lock对象实现同步,下面是代码:
import java.util.concurrent.locks.ReentrantLock;
public class TestSyn {
public static void main(String[] args) {
Account a =new Account(800);
WithDraw w1 = new WithDraw("取现1",a);
w1.start();
WithDraw w2 = new WithDraw("取现2",a);
w2.start();
}
}
class WithDraw extends Thread
{
Account a;
public WithDraw(String name,Account a) {
super(name);
this.a = a;
}
public void run()
{
a.withdraw(800) ;
}
}
//定义一个账户类,用来模拟取现
class Account{
int blance;
//创建可重入锁对象
ReentrantLock lock = new ReentrantLock();
public Account(int blance) {
super();
this.blance = blance;
}
public int getBlance() {
return blance;
}
public void setBlance(int blance) {
this.blance = blance;
}
//定义取款操作
public void withdraw(int money)
{
//进行加锁
lock.lock();
try{
if(money<=blance)
{
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
setBlance(blance-money);
System.out.println("取出"+money+"人民币");
}
else
{
System.out.println("余额不足,请确认");
}
}
finally
{
lock.unlock();
}
}
}