Java多线程同步2——同步方法

java多线程同步除了上文说到的同步代码块,还可以使用同步方法,还是银行取钱的那个问题,代码如下

public class Account

{

private String accountNo;

private double balance;

public Account(){}

public Account(String accountNo , double balance)

{

this.accountNo = accountNo;

this.balance = balance;

}

public void setAccountNo(String accountNo)

{

this.accountNo = accountNo;

}

public String getAccountNo()

{

return this.accountNo;

}

public double getBalance()

{

return this.balance;

}

public synchronized void draw(double drawAmount)

{

if (balance >= drawAmount)

{

System.out.println(Thread.currentThread().getName()

+ "取钱成功!吐出钞票:" + drawAmount);

try

{

Thread.sleep(1);

}

catch (InterruptedException ex)

{

ex.printStackTrace();

}

balance -= drawAmount;

System.out.println("\t余额为: " + balance);

}

else

{

System.out.println(Thread.currentThread().getName()

+ "取钱失败!余额不足");

}

}

public int hashCode()

{

return accountNo.hashCode();

}

public boolean equals(Object obj)

{

if(this == obj)

return true;

if (obj !=null

&& obj.getClass() == Account.class)

{

Account target = (Account)obj;

return target.getAccountNo().equals(accountNo);

}

return false;

}

}

取钱的线程

public class DrawThread extends Thread

{

private Account account;

private double drawAmount;

public DrawThread(String name , Account account

, double drawAmount)

{

super(name);

this.account = account;

this.drawAmount = drawAmount;

}

public void run()

{

account.draw(drawAmount);

}

}

测试类:

public class DrawTest

{

public static void main(String[] args)

{

Account acct = new Account("1234567" , 1000);

new DrawThread("甲" , acct , 800).start();

new DrawThread("乙" , acct , 800).start();

}

}

运行结果:


你可能感兴趣的:(Java多线程同步2——同步方法)