[英]Multi-Thread BufferedReader for reading .txt
I'm wanting to read the line of a .txt do the task, and move on to the next line. 我想阅读.txt行以完成任务,然后移至下一行。
To make the program quicker, I want to multi-thread so each thread tries a line. 为了使程序更快,我想使用多线程,因此每个线程都尝试一行。
The problem is, I don't want the thread 1 trying the same line as thread 2. 问题是,我不希望线程1与线程2尝试同一行。
Any ideas? 有任何想法吗?
I suggest you have one thread doing all the reading, then put the lines into a producer/consumer queue (eg a LinkedBlockingQueue
) - you can then have multiple threads servicing that queue as consumers. 我建议您有一个线程来完成所有读取,然后将这些行放入生产者/消费者队列(例如
LinkedBlockingQueue
)中–然后,您可以有多个线程作为消费者为该队列提供服务。
You really don't want multiple threads performing IO here - even if you had multiple independent BufferedReaders
, if you're reading from traditional disks you don't want to end up seeking in multiple places. 您确实不希望多个线程在这里执行IO-即使您有多个独立的
BufferedReaders
,如果您要从传统磁盘中读取数据,也不想最终在多个位置进行查找。 A producer/consumer queue separates the reading from the handling fairly simply - and makes it easier to test each part in isolation as well. 生产者/消费者队列很简单地将读数从处理中分离出来,并使每个部分的隔离测试变得更加容易。
You can read the lines in one thread and dispatch a worker thread for each line: 您可以在一个线程中读取各行,并为每行分配一个工作线程:
try (BufferedReader reader = new BufferedReader(new FileReader("my.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
new Runnable() {
void run() {
// do stuff with line
}
}.run();
}
}
I have an idea on what you are trying to achieve but not sure how you will code it. 我对您要实现的目标有一个想法,但不确定如何编写代码。 If you can make each thread work on a different set of lines then the threads will not clash.
如果您可以使每个线程在一组不同的行上工作,则这些线程将不会发生冲突。 I mean let thread1 read from 1 to 100, thread2 read from 101 to 200 and so on.
我的意思是让thread1从1读取到100,thread2从101读取到200,依此类推。 At the end join the results of all the threads to get the final result.
最后,加入所有线程的结果以得到最终结果。 Maybe a Fork/Join operation.
也许是Fork / Join操作。
But @Jon comment makes me wary of following such an approach. 但是@Jon的评论使我对遵循这种方法保持警惕。
"You really don't want multiple threads performing IO here - even if you had multiple independent BufferedReaders, if you're reading from traditional disks you don't want to end up seeking in multiple places.. “您真的不希望有多个线程在这里执行IO-即使您有多个独立的BufferedReader,如果您要从传统磁盘中读取数据,也不想最终在多个位置进行查找。”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.