模拟银行转账信息
1、從本地 data.txt 文本中讀取賬戶信息,模擬銀行不同賬戶之間的轉賬。
2、實現代碼如下:
package com.tiger.thread;import java.io.*; /*** 模擬銀行轉賬信息* 從本地 data.txt 文本中讀取賬戶信息* @author tiger* @Date 2017年7月26日 */ public class BankTest extends Thread{public BankTest(String name) {super(name);}public static void main(String[] args) {Bank bank = new Bank();Thread th1 = new Thread(bank,"1號轉賬線路-》");Thread th2 = new Thread(bank,"2號轉賬線路-》");Thread th3 = new Thread(bank,"3號轉賬線路-》");th1.start();th2.start();th3.start();} } /*** @author tiger* @Date 2017年7月26日*/ class Bank implements Runnable{String path = "D:\\Javac\\data.txt";int oneAccount;int twoAccount;int transfer = 100;BufferedReader reader;BufferedWriter writer;//在構造器初始化,為賦值。public Bank() {try {reader = new BufferedReader(new FileReader(path));//讀取 比爾蓋茨 賬戶信息String oneAccount = reader.readLine();//讀取 巴菲特 賬戶信息String twoAccount = reader.readLine();//截取字符數字oneAccount = oneAccount.replaceAll("\\D", "");twoAccount = twoAccount.replaceAll("\\D", "");//將字符串解釋為 int。this.oneAccount = Integer.parseInt(oneAccount);this.twoAccount = Integer.parseInt(twoAccount);} catch (IOException e) {e.printStackTrace();}}@Overridepublic void run() {//同步業務邏輯synchronized ("1") {String name = Thread.currentThread().getName();//模擬 one 給 two 轉錢 turnoneAccount = oneAccount - transfer;twoAccount = twoAccount + transfer; //將轉賬后更新的數據(int類型的轉為String類型)存入data.txt中 String onestr = String.valueOf(oneAccount); String twostr = String.valueOf(twoAccount);try {//writer需要同步writer = new BufferedWriter(new FileWriter(path));writer.write("比爾蓋茨 = " + onestr + " (億美元);");writer.newLine();writer.write("巴菲特 = " + twostr + " (億美元);");writer.close();} catch (IOException e) {e.printStackTrace();}}} }總結
- 上一篇: HDU 3094 树上删边 NIM变形
- 下一篇: C# delegate与event,委托