【发布时间】:2013-09-24 02:18:41
【问题描述】:
我正在创建线程来读取 java 中的文件。当我创建 2 个线程时,每个线程都会读取整个文件,而我希望它们读取文件的不同部分。我尝试输入 sleep()、join()、yield(),但在包含它们之后,它只会减慢读取速度。
public class MyClass implements Runnable {
Thread thread;
public MyClass(int numOfThreads) {
for(int i=0;i < numOfThreads; i++) {
thread = new Thread(this);
thread.start();
}
}
public void run() {
readFile();
}
}
在 readFile 中,在 while 循环中(逐行读取)我调用了 sleep()/yield()。如何让线程读取文件的不同部分?
更新了用于读取文件的方法...
public synchronized void readFile() {
try {
String str;
BufferedReader buf = new BufferedReader(new FileReader("read.txt");
while ((line = buf.readLine()) != null) {
String[] info = str.split(" ");
String first name = info[0];
String second name = info[1];
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
} catch (IOException e) {
System.out.println("Error : File not found");
e.printStackTrace();
}
}
【问题讨论】:
-
读取文件的代码在哪里?
-
公共同步 void readFile() { try{ String str; BufferedReader buf = new BufferedReader(new FileReader("read.txt"); while((line=buf.readLine())!=null) { String[] info = str.split(" "); String first name = info [0]; String second name = info[1]; try{ Thread.sleep(100); } catch(InterruptedException e) { } } catch(IOException e){ System.out.println("Error : File not found" ); e.printStackTrace(); } }
-
您可以使用RandomAccessFile 读取文件中的任意位置,但它不理解“行”。要查找行,您必须扫描整个文件,因为换行可能位于数据中的任何位置。除非是结构化数据。
-
你实际上想用这个来完成什么?
-
您已经可以使用
BufferedReader每秒读取数百万行。这已经足够快了。是什么让您认为多线程会使其更快?
标签: java multithreading