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();
}
}
@Override
public void run() {
//同步业务逻辑
synchronized ("1") {
String name = Thread.currentThread().getName();
//模拟 one 给 two 转钱 turn
oneAccount = 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();
}
}
}
}