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