多线程写文件

public class FileWriteThread implements Runnable {
	
	
	 /**    */
	private static final String SPLIT = "|";

	private String name;

	private OrderManager orderManager;
	
	private long startItem;
	
	public FileWriteThread(String name, OrderManager orderManager, long startItem){
		this.name = name;
		this.orderManager = orderManager;
		this.startItem = startItem;
	}
	
	/**
	 * @see java.lang.Runnable#run()
	 */
	@Override
	public void run() {
		OrderQuery query = new OrderQuery();
		long firstItem = startItem*100000 + 1;
		long lastItem = (startItem+1)*100000;
		query.setFirstItem(firstItem);
		query.setLastItem(lastItem);
		List<Order> orders = orderManager.selectWithPage(query);
		File file = new File("D://1.txt");
		if(!file.exists()){
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		BufferedWriter bufferwriter = null;
		FileWriter filewriter = null;
		StringBuilder sb = new StringBuilder();
		try {
			filewriter = new FileWriter(file, true);//Append
			bufferwriter = new BufferedWriter(filewriter);
			for(Order order: orders){
				sb.append(name).append(SPLIT).append(order.getCardNo()).append(SPLIT)
				.append(order.getFundAccount()).append(SPLIT).append(order.getMisId())
				.append(SPLIT).append(order.getName()).append(SPLIT).append(order.getOrderAmount())
				.append(SPLIT).append(order.getStatus());
				bufferwriter.write(sb.toString());
				bufferwriter.newLine();
				sb.delete(0, sb.length());
			}
			bufferwriter.flush();//刷新流
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				bufferwriter.close();
				filewriter.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public void setOrderManager(OrderManager orderManager) {
		this.orderManager = orderManager;
	}

	public void setStartItem(long startItem) {
		this.startItem = startItem;
	}
}

 

调用端:

@Controller
@RequestMapping("/thread")
public class ThreadPool {
	
	@Autowired
	private OrderManager orderManager;
	
	@RequestMapping("/pool")
	public void pool(ModelMap model) {
		ExecutorService pool = Executors.newSingleThreadExecutor();
		long start = System.currentTimeMillis();
		for(int i=0; i<20; i++)
			pool.execute(new FileWriteThread("线程"+(i+1), orderManager, i));
		System.out.println(System.currentTimeMillis()-start);
	}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值