簡體   English   中英

無法在Java中同時讀取兩個文件

[英]Unable to read two files simultaneously in java

誰能給我通過線程同時讀取兩個文件的工作示例嗎? 以及一次閱讀它們的最佳方式是什么。

public static void main(String args[]) {

         new Runnable(new File("D:/test1.log"),"thread1");
         new Runnable(new File("D:/test2.log"),"thread2");
    }

    private static class Runnable implements Runnable {
        private File logFilePath;
        Thread runner;
        // you should inject the file path of the log file to watch
        public Runnable(File logFilePath,String threadName) {
            this.logFilePath = logFilePath;
            runner = new Thread(this, threadName);
            runner.start();
        }
               _____READ LOGIC HERE____

}

生成日志的程序。我沒有使用任何close或flush。

public final class Slf4jSample {
    static Logger logger = LoggerFactory.getLogger(Slf4jSample.class);
     static int i=0;

    public static void main(final String[] args) {

            int delay = 0; // delay for 5 sec. 


            int period = 10000;  // repeat every sec.
            Timer timer = new Timer();

            timer.scheduleAtFixedRate(new TimerTask() {
                    public void run() {
                        // Task here ...
                        logger.error("error"+i);
                        logger.warn("warn"+i);
                        logger.debug("debug"+i);
                            try{int i=0/0;
                            }catch(Exception e){
                                logger.error("Ecxeption"+i, e);
                            }

                   i++;




                    }
                }, delay, period);
        }
    }

我不太確定簡短說明的目的是什么,但是我只想警告您,從單個硬盤並行讀取文件通常不是一個好主意,因為機械磁盤磁頭需要尋找下一個讀取對象位置,因此使用多個線程進行讀取會導致其不斷跳動並放慢速度,而不是加快速度。

如果您想讀取文件的一部分並以並行方式處理它們,建議您查看一個生產者(按順序讀取文件)和多個使用者(處理文件)的解決方案。

編輯 :如果您堅持使用多個閱讀器,則可能應該這樣更改代碼:

public static void main(String args[]) {

     new Thread(new ThreadTask(new File("D:/test1.log")),"thread1").start();
     new Thread(new ThreadTask(new File("D:/test2.log")),"thread2").start();
}

private static class ThreadTask implements Runnable {
    private File logFilePath;        

    // you should inject the file path of the log file to watch
    public ThreadTask(File logFilePath) {
        this.logFilePath = logFilePath;
    }

    public void run() {
        // read file
    }
}

您必須實例化諸如Thread t = new Thread(new Runnable(.....))線程對象,並將可運行對象傳遞給Thread的構造函數。 然后在線程對象上調用start方法將啟動單獨的線程並調用Runnable的run方法。

您不應該在Runnable的構造函數中創建新線程。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM