[英]Does thread used in @Scheduled annotation released to pool before finishing execution?
[英]Thread finishing execution before printing
我執行一些代碼時正在寫文件(Java)。 在下面,您可以找到所使用的代碼,該代碼由JVM調用的“線程B”執行。
writer = new PrintWriter(new BufferedWriter(new FileWriter("table.csv")));
(...)
while ( (m_bEnExecution) && (!m_bFinTestRules) ) {
//Calculate new rule
CalculateNewRule(writer);
}
writer.close();
在CalculateNewRule方法內部,創建了一個AssociationRule的新實例,它將接收writer作為實例變量。 AssociationRule內部的功能之一是進行打印。
writer.println(outputRule);
writer.flush();
問題似乎是此函數由AWT線程調用,並且永遠不會寫入CalculateNewRule(writer)方法內部要寫入文件的最后一行,除非我明確地強制線程的執行停止,在while周期之后。 對可能是什么問題有任何想法嗎? 有什么優雅的方法可以解決這個問題嗎?
在一個答案中,有人建議將打印線程設置為守護程序線程,但是我不知道如何在該特定線程上執行此操作。
在此線程完成之前,可能是調用線程即將結束。 在這種情況下,請使用守護程序線程。 提供更多詳細信息也許我們可以提供幫助。
那是((m_bEnExecution)&&(!m_bFinTestRules)”始終等於true嗎?
我建議如下:
try {
while ( (m_bEnExecution) && (!m_bFinTestRules) ) {
//Calculate new rule
CalculateNewRule(writer);
writer.flush();
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
writer.close();
}
但是您仍然需要確保不會造成無限循環。
您提供的代碼不多,但是無論如何。
你什么意思:
強制線程執行停止
您使用的是BufferedWriter
因此除非flush
, close
Writer等,否則您不確定它是否已將所有內容寫入緩沖區。
如果要確定,請選擇以下方法之一。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.