[英]Java implementing multiple threads (excel processing)
因此,我的應用程序允許用戶選擇通常具有300至5000行的Microsoft excel文件。 有時甚至大於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使其運行。 可用時,它將自動分配您發送到Thread
的新Runnable。
你可以啟動一個ExecutorService
只是通過調用帶有一個固定數量的線程Executors.newFixedThreadPool(int numThreads)
然后只需調用submit(Runnable runnableWithYourProcessing)
。 完成后,別忘了shutdown()
!
我將按以下方式進行操作:
Callable
接口並返回String
的Task類 ExecutorService
,並為Excel工作表中的每一行提交Task實例。 Callable
返回的Future<String>
,並將這些值連接起來以獲得結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.