java - java中使用Thread来读写文件

标签 java multithreading

我想制作一个程序,逐行读取文件,然后将这些行写入另一个文件。我想使用两个单独的线程来解决这个问题。第一个线程读取一行,然后将其传递给另一个线程,另一个线程负责通过消息将该行写入另一个文件。应重复此过程直到到达文件末尾。

我该怎么做?

最佳答案

你想要的是 producer-consumer model 。使用两个 Thread 对象和 ArrayBlockingQueue 来实现这一点并不难。 。这是一些启动代码:

// we'll store lines of text here, a maximum of 100 at a time
ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<String>(100);

// code of thread 1 (producer)
public void run() {
   while(/* lines still exist in input file */) {
       String line = // read a line of text
       queue.put(line); // will block if 100 lines are already inserted
   }
   // insert a termination token in the queue
}

// code of thread 2 (consumer)
public void run() {
   while(true) {
       String line = queue.take(); // waits if there are no items in the queue
       if(/* line is termination token */) break;
       // write line to file
   }   
}

希望这有帮助。我无法提供完整的代码,最好您自己尝试填补空白。

关于java - java中使用Thread来读写文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10877002/

相关文章:

java - 应用带有两个变量的 sparql 并在 java 变量中返回结果

java - Amazon ec2 上的 Jhipster 应用程序内存消耗

java - 不懂Thread o/p

c# - 在 C#/Xamarin 中等待线程完成

java - spring-boot-maven-plugin :2. 0.0.RELEASE:重新打包失败:无法重命名

java - 如何创建分组 Swagger 注释 - 此位置不允许使用注释

javascript - 为什么在 Selenium Webdriver (Java) 中 Gmail 密码字段无法发送带有 "sendkeys"的 key ?

c++ - 是否有提供 C++ <Thread> 支持的 IDE?

java - 当作业到达 threadPoolExecution 时调用所有线程

C# 从构造函数中调用事件