我有創建多個線程不已的應用程序。每個線程讀取一些信息,並使用線程池創建了一些任務(這很好)。的Java線程多文件保存
我們添加了處理數組,當它完成附加功能,它把那些ArrayList
s到新的線程,這些列表保存爲文件。我以3種方式實施了儲蓄,其中只有一種成功。我想知道爲什麼其他兩種方式沒有。
我創建了一個線程(通過
new Thread(Runnable)
),並給它一個文件的數組和名稱。在線程構造函數中,我創建了PrintWriter
並保存了這些文件。它運行沒有任何問題。 (我有1-10個文件保存線程並行運行)。如果我在
Run
方法中放置保存代碼outputStream.println(aLog);
,它永遠不會達到它,並且在構造函數完成線程退出之後。我將創建的runnables(文件保存)放入線程池(並且保存的代碼位於
run()
方法中)。當我只發送1個任務(1個文件保存)時,一切正常。 1個多任務被添加到池(非常快),創建異常(在調試時,我可以看到所有需要的信息是可用的)和一些文件都不會保存。
是否可以解釋差異行爲? 感謝
請看下面的代碼。 (從正被無端螺紋類也放置在池中的某些任務的一部分功能),在所述環形線程創建的池: ExecutorService的iPool = Executors.newCachedThreadPool();
private void logRate(double r1,int ind){
historicalData.clear();
for (int i = 499; i>0; i--){
// some Code
Data.add(0,array1[ind][i][0] + "," + array1[ind][i][1] + "," +
array1[ind][i][2] + "," + array1[ind][i][3] + "," +
array2[ind][i] + "\n");
}
// first item
array1[ind][0][0] = r1;
array1[ind][0][1] = array1[ind][0][0] ;
array1[ind][0][2] = array1[ind][0][0] ;
array2[ind][0] = new SimpleDateFormat("HH:mm:ss yyyy_MM_dd").format(today);
Data.add(0,r1+","+r1+","+r1+","+r1+ "," + array2[ind][0] + '\n') ;
// save the log send it to the pool (this is case 3)
//iPool.submit(new FeedLogger(fName,Integer.toString(ind),Data));
// Case 1 and 2
Thread fl = new Thread(new FeedLogger(fName,Integer.toString(ind),Data)) ;
}
這裏是FeedLogger類:
public class FeedLogger implements Runnable{
private List<String> fLog = new ArrayList<>() ;
PrintWriter outputStream = null;
String asName,asPathName;
public FeedLogger(String aName,String ind, List<String> fLog) {
this.fLog = fLog;
this.asName = aName;
try {
asPathName = System.getProperty("user.dir") + "\\AsLogs\\" + asName + "\\Feed" + ind
+ ".log" ;
outputStream = new PrintWriter(new FileWriter(asPathName));
outputStream.println(fLog); Case 1 all is fine
outputStream.flush(); // Case 1 all is fine
outputStream.close(); Case 1 all is fine
}
catch (Exception ex) {
JavaFXApplication2.logger.log(Level.SEVERE, null,asName + ex.getMessage());
}
}
@Override
public void run()
{
try{
outputStream.println(fLog); // Cas2 --> not reaching this code, Case3 (as task) create
exception when we have multiple tasks
outputStream.flush();
}
catch (Exception e) {
System.out.println("err in file save e=" + e.getMessage() + asPathName + " feed size=" +
fLog.size());
JavaFXApplication2.logger.log(Level.ALL, null,asName + e.getMessage());
}
finally {if (outputStream != null) {outputStream.close();}}
}
}
可以此[示例](http://arashmd.blogspot.com/2013/07/java-thread-example.html#fe)的幫助。 – 2013-10-16 20:40:28
你是否在第二種方式在線程中調用了'.start()'? – vandale
關於案例2 - 你是對的,我的錯誤。任何想法爲什麼異常發生在案例3時,我使用線程池 – user2319608