import java.util.concurrent.locks.reentrantlock;
public class account
{
/**
* 同步锁
*/
private final reentrantlock lock = new reentrantlock();
* 账户号
private string accountno;
* 账户余额
private double balance;
public account()
{
super();
}
public account(string accountno, double balance)
this.accountno = accountno;
this.balance = balance;
@override
public int hashcode()
return accountno.hashcode();
public boolean equals(object obj)
if (null != obj && obj.getclass() == account.class)
{
account target = (account) obj;
return target.accountno.equals(accountno);
}
return false;
* 同步方法,同步方法的监视器是this,同步方法可以将该类变为线程安全的类
* 任何时候只有一个线程获得对account对象的锁定,然后进入draw方法进行取钱
public void draw(double drawamount)
lock.lock();
try
if (balance >= drawamount)
{
system.out.println(thread.currentthread().getname() + "取出钞票成功" + drawamount);
balance -= drawamount;
system.out.println("余额为" + balance);
}
else
system.out.println("余额不足");
finally
// 用finally块保证释放锁
lock.unlock();
/* 只提供getters,不提供setters,确保安全*/
public string getaccountno()
return accountno;
public double getbalance()
return balance;
}
public class drawthread extends thread
* 模拟账户
private account ac;
* 当前取钱线程希望取得的钱数
private double drawamount;
public drawthread(string name, account ac, double drawamount)
super(name);
this.ac = ac;
this.drawamount = drawamount;
public void run()
ac.draw(drawamount);
public class test
public static void main(string[] args)
account ac = new account("00000001", 1000);
thread t1 = new thread(new drawthread("lily", ac, 800));
thread t2 = new thread(new drawthread("tom", ac, 800));
t1.start();
t2.start();