Daily Archives: June 4, 2019

Java – Runtime.getRuntime().addShutdownHook()

a useful method when program done and run last step task.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
 
 
public class AddShutdownHookTest {
 
	static class Message extends Thread {
 
		public void run() {
			System.out.println("Bye.");
		}
	}
 
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {
 
			// register Message as shutdown hook
			Runtime.getRuntime().addShutdownHook(new Message());
 
			// print the state of the program
			System.out.println("Program is starting...");
 
			// cause thread to sleep for 3 seconds
			System.out.println("Waiting for 3 seconds...");
			Thread.sleep(3000);
 
			// print that the program is closing
			System.out.println("Program is closing...");
 
		} catch (Exception e) {
			e.printStackTrace();
		}
	}