我已經閱讀了關於使用多線程讀取文件的一些答案,並且還發現它的效率非常差,但仍然爲了學習,我正嘗試使用多線程讀取文件,即針對大文件很少的記錄應該由另一個線程讀取。在java中使用多線程讀取txt文件
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class QueueThread implements Runnable {
int count=0;
private int start;
private int end;
public QueueThread(int start,int end) {
this.start=start;
this.end=end;
}
public void run() {
for(int i=start;i<end;i++) {
try {
Scanner read = new Scanner (new File("userinfo.txt"));
read.useDelimiter(",|\n");
String mobile,recharge;
while(read.hasNext())
{
mobile = read.next();
recharge =read.next();
ArrayList<String> words = new ArrayList<String>();
words.add(mobile+recharge);
count++;
System.out.println("mobile no.:"+ mobile);
System.out.println("recharge amount:"+ recharge);
System.out.println("count:"+ count);
}
read.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Control.java:
public class Control {
public static void main(String args[]) throws InterruptedException
{
QueueThread r1=new QueueThread(0,15);
QueueThread r2=new QueueThread(15,30);
Thread t1 =new Thread(r1);
Thread t2 =new Thread(r2);
t1.start();
t2.start();
t1.join();
t2.join();
}
}
我在這裏讀文件userinfo.txt用一些隨機的10位無。和一些號碼。每個線程讀取整個文件,而不是隻讀取一個線程中的前15個條目和另一個線程中的其他14個條目,我相信這並不會破壞我並行讀取文件的座右銘。 我也試圖將提取的數據存儲在ArrayList中以對其執行進一步的操作。
userinfo.txt
9844794101,43
9844749102,54
9844741903,55
9844741094,33
9844741095,87
9844741068,32
9844974107,53
8848897101,343
8848891702,345
8848891063,34
8848849104,64
我真的很需要一些出路在不同的線程同時讀取該文件
電流輸出上
mobile no.:9844794101
recharge amount:43
mobile no.:9844794101
count:1
recharge amount:43
count:1
mobile no.:9844749102
recharge amount:54
mobile no.:9844749102
recharge amount:54
count:2
count:2
等等
我不知道爲什麼最近有很多關於多線程閱讀的問題(請看右邊的相關問題)。因爲I/O硬件(磁盤,數據總線,...)是瓶頸而不是CPU,所以通常沒有多少好處。 – Henry
爲了學習*什麼*?您可以在單個線程中每秒讀取數百萬行。通過將問題分成線程,你甚至希望獲得什麼,甚至在智力上? – EJP
如果你想了解多線程,閱讀一個相對較小的文件不是正確的問題。 –