[code="java"]
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.text.SimpleDateFormat;
public class Main {
public static void main(String[] args) throws Exception{
File file = new File(""/*文件地址*/);
long start = System.currentTimeMillis();
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
Map lines = new ConcurrentHashMap();
for(int i = 0; i < 5; i++){/*这里修改线程数*/
Thread t = new Thread(new LineParser(br,lines));
t.start();
}
long end = System.currentTimeMillis();
System.out.println(end-start);
}
}
class LineParser implements Runnable{
LineParser(BufferedReader br,Map lines){
this.br = br;
this.lines = lines;
}
public void run(){
try{
String line;
while((line = br.readLine()) != null){
long time = DataParser.parse(line.substring(0,line.indexOf(" ")));
String eventString = line.substring(line.indexOf(" ")+2,line.length());
lines.put(time, eventString);
Timer.tick(System.currentTimeMillis());
}
if(line == null){
SimpleDateFormat sdft = new SimpleDateFormat("HH:mm:ss");
System.out.println(sdft.format(new Date(Timer.cost())));
}
}
catch(Exception e){}
}
BufferedReader br;
Map lines;
}
class Timer{
public synchronized static void tick(long time){
if(time>max)max = time;
if(min == 0||(time<min))min = time;
}
public static long cost(){
System.out.println(min);
System.out.println(max);
return max-min;
}
private static long max = 0;
private static long min = 0;
}
[/code]
我本来想测试一下看多线程处理文件对速度会不会有很大提升,结果做了这个测试,里面的计时方法可能会有一点偏差,但是在测试中引入了资源消耗的问题,当我开一个线程时候,资源占用在25%,开到10,100时候,CPU资源消耗高达80-90%,这样就算能减少处理文件的时间,恐怕也不能在实际中运用,还请有相关经验的朋友能够对这个程序给点建议。先谢过了。