因此,我的应用程序允许用户选择 Microsoft Excel 文件,通常有 300 到 5000 行。有时甚至超过 5000。我的问题是在这种情况下使用多个线程是否会更有效,以及利用线程的最有效方法是什么。每个文件应该有自己的线程还是什么?这也是每个 Excel 文件的处理方式:
Load file
loop until eof
iterate through rows and cells
Assign each cell to variable x
concatenate required chars to begin and end of x
Append x to y
End loop
Write y to text file
编辑代码
public class FileParse implements Callable<String>
{
private String fPath;
private BufferedReader br;
private String line;
@Override
public String call()
{
line = "";
try{
br = new BufferedReader(new FileReader(fPath));
String sCurrentLine = "";
while ((sCurrentLine = br.readLine()) != null) {
line += sCurrentLine;
}
}catch(IOException exc){
System.out.println("Cant load file");
}
return line;
}
public FileParse (String location)
{
br = null;
fPath = location;
}
public static void main(String[] args)
{
ExecutorService executor = Executors.newFixedThreadPool(10);
Callable<String> t1 = new FileParse("rsrc\\data12.txt");
Callable<String> t2 = new FileParse("rsrc\\data13.txt");
Future<String> fut1 = executor.submit(t1);
Future<String> fut2 = executor.submit(t2);
try{
System.out.println(fut1.get());
System.out.println(fut2.get());
}catch(InterruptedException | ExecutionException e){
}
executor.shutdown();
}
}
最佳答案
使用多线程会更快,是的。每个文件一个线程听起来不错,但您仍然需要某种限制(太多线程会带来很多问题)。
我建议你尝试一下ExecutorService
,并实现Runnable
并发送 Runnables 让它运行。当线程
可用时,它会自动将您发送的新 Runnable 分配给该线程。
您只需调用 Executors.newFixedThreadPool(int numThreads)
即可启动具有固定数量线程的 ExecutorService
。然后只需调用submit(Runnable runnableWithYourProcessing)
。完成后不要忘记shutdown()
!
关于Java实现多线程(excel处理),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22850680/