繁体   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