[英]Why is the ScheduledExecutorService not working as expected?
[英]ScheduledExecutorService not working as expected
在執行以下代碼時,語句System.out.println("completed"); 即使延遲設置為 0,也會在執行程序之前執行。為什么會這樣? 這里怎么能維持秩序?
public class TestMyClass {
private static int count = 0;
public static void main(String args[]) {
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
Runnable periodicTask = () -> {
try {
List<String> lines = Files.readAllLines(new File("E:\\MyFile.log").toPath());
String key = "FIND ME";
System.out.println("text not found");
for (String line : lines) {
if (line.contains(key)) {
count++;
System.out.println("found text ..." + count);
executor.shutdown();
}
}
} catch (IOException e) {
e.printStackTrace();
}
};
executor.scheduleAtFixedRate(periodicTask, 0, 5, TimeUnit.SECONDS);
System.out.println("completed");
}
}
檢查條件while(.executor.isTerminated())完成工作。 它確保僅在執行程序完成其工作后才執行下一條語句。
原因在於多任務/線程的本質。 ScheduledExecutorService
啟動一個新線程來執行您的Runnable
。 獨立於此,您的主程序在其自己的/原始線程中繼續其工作。
主線程和可運行線程都將並行處理。
在你的情況下, System.out.println("completed");
執行速度比讀取文件的Runnable
更快。
現在,這取決於您想要實現的目標。 正如您已經寫過的那樣,您可以阻止您的主程序,例如使用循環並等待執行程序完成所有執行。 但這不是你通常做的,因為那樣你就可以在同一個線程中執行代碼。
通常,您使用多線程來並行執行代碼或不阻塞任務/線程,例如調用 web 服務並繼續做一些其他事情。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.