1、建立java類
這裡建立了三個java類,第一個Account類,用於封裝帳戶中的各種資訊;第三個DrawThread類別用於實作執行緒體;第二個類別主要封裝了主函數
#2、Account類別
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 void setBalance(double balance){ this.balance=balance; } public String getAccountNo(){ return accountNo; } public double getBalance(){ return balance; } 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; } }
##3 、DrawThread類別
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作为同步监视器,任何线程进入下面同步代码块之前 //必须先获得对account账户的锁定——其他线程无法获得锁,也就无法修改它 synchronized (account) { if (account.getBalance() >= drawAmount) { //吐出钞票 System.out.println(getName() + "取钱成功!吐出钞票:" + drawAmount); /* try { Thread.sleep(1); }catch (InterruptedException ex) { ex.printStackTrace(); } */ //修改余额 account.setBalance(account.getBalance() - drawAmount); System.out.println("\t余额为:" + account.getBalance()); } else { System.out.println(getName() + "取钱失败!余额不足!"); } } } }
4、DrawTest類別
public class DrawTest { public static void main(String[] args){ //创建一个账户 Account acct=new Account("1234567",1000); //模拟两个线程对同一个账户取钱 new DrawThread("jack",acct,800).start(); new DrawThread("rose",acct,800).start(); } }
synchronized (obj){ //需要执行的代码 }
Account acct=new Account("1234567",1000); new DrawThread("jack",acct,800).start(); new DrawThread("rose",acct,800).start();
以上是java多執行緒怎麼實作取款小程序的詳細內容。更多資訊請關注PHP中文網其他相關文章!