模拟银行转账信息

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();
			}
		}
	}
}




  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ljt-tiger

thanks

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值