java中无法同时读取两个文件

发布于 2024-12-27 19:37:14 字数 1621 浏览 1 评论 0原文

谁能给我通过线程同时读取两个文件的工作示例?以及一次性阅读它们的最佳方式是什么。

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 或lush 。

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

Can anyone give me the working example of reading two files simultaneously through threads? and also what would be the best way to read them at one time.

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____

}

Program that generates logs.I am not using any close or 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);
        }
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

已下线请稍等 2025-01-03 19:37:14

从简短的描述中我不太确定你的目的是什么,但我只是想警告你,从单个硬盘并行读取文件通常不是一个好主意,因为机械磁盘头需要寻找下一个读取位置,因此使用多个线程读取将导致它不断跳动并减慢速度而不是加快速度。

如果您想读取部分文件并并行处理它们,我建议您查看单个生产者(顺序读取文件)多个消费者(处理文件)解决方案。

编辑:如果您坚持使用多个阅读器,您可能应该像这样更改代码:

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

I'm not quite sure what your aim is from the short description, but I just want to warn you that reading files in parallel from a single hard disk is generally not a good idea, because the mechanical disk head needs to seek the next reading location and so reading with multiple threads will cause it to keep bouncing around and slow things down instead of speeding them up.

In case you want to read portions of files and process them in paralle, I recommend you to look at a single producer (to read the files sequentially) multiple consumer (to process the files) solution.

Edit: If you insist on using multiple readers, you should probably change your code like this:

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
    }
}
绻影浮沉 2025-01-03 19:37:14

您必须实例化一个线程对象,例如 Thread t = new Thread(new Runnable(.....))
并在 Thread 的构造函数中传递可运行对象。
然后调用线程对象的start方法将启动单独的线程并调用Runnable的run方法。

您不应该在 Runnable 的构造函数内创建新线程。

You have to instantiate a thread object like Thread t = new Thread(new Runnable(.....))
and pass runnable object in Thread's constructor.
Then calling start method on thread object will start separate thread and calls Runnable's run method.

You shouldn't be creating new threads inside Runnable's constructor.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文