刚刚写了个测试程序 原本想使用多线程并发处理 来节省时间,结果反而更耗时。请各位指点一下。
主方法:
public class MainAction {
public static void main(String[] args) {
/*new Action1().run();
new Action2().run();
new Action3().run();*/
new Thread(new Action1()).start();
new Thread(new Action2()).start();
new Thread(new Action3()).start();
}
}
Action1 /2/3(方法一样,只是文件大小不同):
public class Action1 implements Runnable{
public void run() {
System.out.println("start 1..........");
long start1 = System.currentTimeMillis();
writeToTxt("123");
Context.flg1 = 1;
long end1 = System.currentTimeMillis();
float second1 = (end1 - start1) / 1000F;
System.out.println("end 1 cost " + second1 + " s");
}
public void writeToTxt(String text){
File file = new File("D:/1.txt");
FileWriter fw = null;
BufferedWriter writer = null;
try {
fw = new FileWriter(file);
writer = new BufferedWriter(fw);
for (int i=0;i<200*1000*10;i++) {
writer.write(text);
writer.newLine();//换行
}
writer.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}finally{
try {
writer.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
运行结果:
start 1..........
start 2..........
start 3..........
end 2 cost 89.906 s
end 3 cost 115.905 s
end 1 cost 163.817 s
如果使用上面注掉的串行 运行:
start 1..........
end 1 cost 13.681 s
start 2..........
end 2 cost 18.752 s
start 3..........
end 3 cost 20.051 s
求解,是不是程序并没有真正的多线程去执行。
另外,如果Action1/2/3 是3个远程调用,能否达到节省时间的效果?