在 Java 中,關閉掛鉤為應用程式提供了一種在終止時執行清理任務的方法。這對於確保程式在意外中斷時正常關閉非常有用。
考慮以下將數位批次寫入檔案的應用程式:
<code class="java">import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintWriter; public class GracefulShutdownTest1 { private final File f; private final int N; public GracefulShutdownTest1(File f, int N) { this.f = f; this.N = N; } public void run() { try (PrintWriter pw = new PrintWriter(new FileOutputStream(f))) { for (int i = 0; i < N; ++i) { writeBatch(pw, i); } } catch (FileNotFoundException e) { e.printStackTrace(); } } private void writeBatch(PrintWriter pw, int i) { for (int j = 0; j < 100; ++j) { pw.write(Integer.toString(i * 100 + j)); if ((j + 1) % 10 == 0) { pw.write('\n'); } else { pw.write(' '); } } } public static void main(String[] args) { if (args.length < 2) { System.out.println("args = [file] [N] " + "where file = output filename, N=batch count"); } else { new GracefulShutdownTest1(new File(args[0]), Integer.parseInt(args[1])).run(); } } }</code>
要將關閉鉤子整合到在此應用程式中,請按照以下步驟操作:
<code class="java">private static volatile boolean keepRunning = true; // ... public void run() { try (PrintWriter pw = new PrintWriter(new FileOutputStream(f))) { for (int i = 0; i < N && keepRunning; ++i) { writeBatch(pw, i); } } catch (FileNotFoundException e) { e.printStackTrace(); } } // ... public static void main(String[] args) { final Thread mainThread = Thread.currentThread(); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { keepRunning = false; mainThread.join(); } }); new GracefulShutdownTest1(new File(args[0]), Integer.parseInt(args[1])).run(); }</code>
透過實現關閉鉤子,您可以提供更具彈性的在終止之前執行必要的清理任務的應用程式。
以上是如何使用 Java 中的關閉鉤子來確保應用程式正常終止,尤其是在處理檔案操作時?的詳細內容。更多資訊請關注PHP中文網其他相關文章!