long start = System.currentTimeMillis();
// ... 業務邏輯 ...
long end = System.currentTimeMillis();
System.out.println("程序運行時長: " + (end - start) + " ms");
String fileName = "/home/test";
FileWriter writer = null;
public void writeToFile() {
try {
writer = new FileWriter(fileName, true); // true = 追加模式
writer.write("Hello World!");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null) try { writer.close(); } catch (IOException ignore) {}
}
}
boolean flag = true;
// ... 業務邏輯 ...
if (condition) {
// ...
flag = false; // 根據邏輯修改
} else {
// ...
}
注意: true/false 語義需明確文檔化,否則邏輯錯誤極難排查。
HashMap<String, String> myMap = new HashMap<>();
// 學號 → 姓名
myMap.put("1", "張三");
myMap.put("2", "李四");
myMap.put("3", "王五");
myMap.put("4", "趙六");
String name = myMap.get("1"); // 返回 "張三"
String path = "/home/allNumber.csv";
public static ArrayList<String> myList = new ArrayList<>();
public static void createList(String path) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(new File(path)));
String line;
while ((line = reader.readLine()) != null) {
if (!myList.contains(line)) { // 去重
myList.add(line);
}
}
reader.close(); // 必須關閉流
}
優化建議: 大數據量用 HashSet 去重再轉 List,O(1) 查重優於 O(N)。
public class TimedWriter {
public static void executeFixedRate() throws IOException {
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
// 參數:任務、首次延遲、間隔、時間單位
executor.scheduleAtFixedRate(new LogTask(), 0, 5000, TimeUnit.MILLISECONDS);
}
static class LogTask implements Runnable {
private String fileName = "/home/test";
private FileWriter writer = null;
private static DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public void run() {
try {
writer = new FileWriter(fileName, true);
writer.write("Hello World " + df.format(new Date()) + "\n");
writer.flush(); // 確保寫入磁盤
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws Exception {
executeFixedRate();
// 主線程不退出,定時任務持續運行
Thread.currentThread().join();
}
}
public class DailyTimerWriter {
private static void executeFixedRate() {
Timer timer = new Timer();
Calendar cal = Calendar.getInstance();
// 設置為每日 00:00:00
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
Date firstTime = cal.getTime();
Date now = new Date();
long interval = firstTime.getTime() - now.getTime();
// 若今日已過,推遲到明天
if (interval < 0) {
cal.add(Calendar.DAY_OF_MONTH, 1);
firstTime = cal.getTime();
interval = firstTime.getTime() - now.getTime();
}
// 每 24 小時執行一次
timer.schedule(new LogTask(), interval, 24 * 60 * 60 * 1000);
}
static class LogTask extends TimerTask {
// 同方案一的 run 邏輯
public void run() { /* 寫文件邏輯 */ }
}
}
| 特性 | ScheduledExecutorService | Timer |
|---|---|---|
| 線程模型 | 線程池,可多線程 | 單後台線程 |
| 異常處理 | 異常不影響後續任務 | 任務拋異常導致 Timer 失效 |
| 精度 | 較高 | 較低 |
| 推薦場景 | 高併發、長時間運行 | 簡單定時、輕量級 |
最佳實踐: 生產環境優先使用 ScheduledExecutorService 或 Spring @Scheduled、Quartz 等成熟調度框架。