多線程讀寫文件


 //主函數
  public static void main(String[] args) throws Exception {
        long startTime = System.currentTimeMillis();

        // String localFilePath = localTempPath+"/"+fileName;
        String localFilePath = "讀取文件地址";

        ReadFile(startTime, localFilePath);

    }



  

//讀文件  
 private static void ReadFile(long startTime, String localFilePath) throws IOException {
        // 開啟固定線程池
        //每個機器測試時間不同僅供參考
        //9s    定長線程池
        //ExecutorService exec = Executors.newFixedThreadPool(48);

        //9s    緩存線程池
        //ExecutorService exec = Executors.newCachedThreadPool();

        //11s   周期線程池
        //ExecutorService exec = Executors.newScheduledThreadPool(48);

        //18S   單例線程池
        ExecutorService exec = Executors.newSingleThreadExecutor();


        List<String> dataList = new ArrayList<>();
        // 逐行讀取本地文件
        File f = new File(localFilePath);
        //讀取文件
        InputStreamReader reader = new InputStreamReader(new FileInputStream(f), "UTF-8");
        BufferedReader br = new BufferedReader(reader);
        String str = null;
        // 定義計數器
        int i = 0;
        //判斷空行
        while ((str = br.readLine()) != null) {
            // i的值是從1開始
            i++;
            // 加入集合
            dataList.add(str);
            if (i % 100 == 0) {
                System.out.println("成百計時:"+i);
                // 每次傳入線程的集合
                List<String> onceList = new ArrayList<>();
                for (String item : dataList) {
                    onceList.add(item);
                }
                // 清空集合
                dataList = null;
                // 重構集合
                dataList = new ArrayList<String>();

                Map<String, Object> pMap = new HashMap<>();
                // 開啟線程
                Runnable task = new BatchHandlerThreadTask(onceList, pMap);
                exec.submit(task);
            }
        }
        reader.close();
        br.close();

        // 判斷最后一次
        if (dataList.size() != 0) {
            Map<String, Object> pMap = new HashMap<>();
            Runnable task = new BatchHandlerThreadTask(dataList, pMap);
            exec.submit(task);
        }

        exec.shutdown();

        /*
         *
        isShutDown當調用shutdown()或shutdownNow()方法后返回為true。
        isTerminated當調用shutdown()方法后,並且所有提交的任務完成后返回為true;
        isTerminated當調用shutdownNow()方法后,成功停止后返回為true;
         */
        while (true) {
            if (exec.isTerminated()) {
                System.out.println("全部線程都結束了,i: "+i+"----耗時:"+(System.currentTimeMillis()-startTime)/1000+"s");
                break;
            }
        }
    }

  



import java.io.*;
import java.util.List;
import java.util.Map;



/**
* 實現Runnable接口 * @Auther Qianxy * @Date 2020/7/3 */ public class BatchHandlerThreadTask implements Runnable { //待處理數據集合 private List dataList; //其他參數Map private Map paramMap; public BatchHandlerThreadTask() { super(); } public BatchHandlerThreadTask(List dataList, Map paramMap) { super(); this.dataList = dataList; this.paramMap = paramMap; } public List getDataList() { return dataList; } public void setDataList(List dataList) { this.dataList = dataList; } public Map getParamMap() { return paramMap; } public void setParamMap(Map paramMap) { this.paramMap = paramMap; }   //寫文件 public void writeListToFile(List<String> dataList) { // 要寫入的文件路徑 File file = new File("寫入文件地址"); // 判斷文件是否存在 if (!file.exists()) { try { // 如果文件不存在創建文件 file.createNewFile(); System.out.println("文件"+file.getName()+"不存在已為您創建!"); } catch (IOException e) { System.out.println("創建文件異常!"); e.printStackTrace(); } } else { System.out.println("文件"+file.getName()+"已存在!"); } FileOutputStream fos = null; PrintStream ps = null; // 遍歷listStr集合 for (String str : dataList) { try { // 文件輸出流 fos = new FileOutputStream(file,true);//追加 ps = new PrintStream(fos); } catch (FileNotFoundException e) { e.printStackTrace(); } // +換行 String string = str + "\r\n"; // 執行寫操作 ps.print(string); } // 關閉流 ps.close(); System.out.println("文件寫入完畢!"); } @Override public void run() {
     //記時間 long t1 = System.currentTimeMillis(); //寫入文件 writeListToFile(dataList); System.out.println("--h--線程名: " + Thread.currentThread().getName() + "--當前線程耗時:" + (System.currentTimeMillis() - t1)/1000 + "s" + "--當前批次處理總數據" + dataList.size()); } }

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM