gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 19:04:07 26 4
gpt4 key购买 nike

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

我该怎么做?

最佳答案

你想要的是 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com