本文介绍了读取单个文件的Java多线程应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前编写的程序使用32个线程并为每个线程读取1个文件(因此32个.txt文件)。多线程与CPU速度无关,但每秒对BING的api进行32次调用比制作1.每个.txt文件包含搜索查询列表要快得多。我创建一个线程,它从文件中一次读取一行。是否可以创建所有32个线程并将它们指向单个.txt文件?

I currently wrote my program to use 32 threads and read 1 file per thread (so 32 .txt files). The multi-threading has nothing to do with CPU speed, but making 32 calls to BING's api per second is a lot faster than making 1. Each of the .txt files containing a list of search queries. I create a thread it reads one line at a time from it's file. Is it possible to create all 32 threads and point them to a single .txt file??

推荐答案

使用Producer-Consumer模式。只有一个线程可以读取文件并将每个行/命令推送到(线程安全读写)使用。

Use the Producer-Consumer pattern. Have only one thread that reads file and pushes each line/command into ArrayBlockingQueue (thread safe read and write) using put().

所有其他32个线程应通过调用从同一队列对象中读取。如果队列为空,它们将阻塞,这很好。

All other 32 threads should read from the same queue object by calling take(). They will block if queue is empty, which is nice.

这个解决方案更好,因为磁盘本质上是单线程的,所以你不会通过读取文件获得太多同时。

This solution is better because the disk is inherently single-threaded so you won't get much by reading the file concurrently.

这篇关于读取单个文件的Java多线程应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 01:43