The Java. Lang. runtime class provides an addshutdownhook () method. Add a VM to close the hook. It has the following purposes:
① The application Exits normally. Only specific business logic is required when exiting.
② The VM exits abnormally. If you press the CTRL + C key, the operating system is disabled. Execute necessary rescue measures when exiting. We can place the exit event in the thread body of a custom thread.
The following code demonstrates testonexit]
/** <Br/> * testonexit. java <br/> * copyright (c) 2011 cuiran2001@163.com <br/> * Create: cui ran 2011-1-12 09:23:37 <br/> */</P> <p> package COM. cayden. thread724; </P> <p>/** <br/> * @ author Cui ran <br/> * @ version 1.0.0 <br/> * @ DESC <br/> */ <br/> public class testonexit {</P> <p> Public testonexit () {<br/> doshutdownwork (); <br/>}< br/> private void doshutdownwork () {<br/> runtime. getruntime (). addshutdownhook (New thread () {<br/> Public void run () {<br/> system. out. println ("response to application exit event"); <br/>}< br/> }); <br/>}< br/>/** <br/> * @ Param ARGs <br/> */<br/> Public static void main (string [] ARGs) throws interruptedexception {<br/> // todo auto-generated method stub <br/> testonexit testor = new testonexit (); <br/> long begintime = system. currenttimemillis (); <br/> for (INT I = 0; I <10; I ++) {<br/> thread. sleep (1000); <br/> system. out. println ("I =" + I); <br/>}< br/> long endtime = system. currenttimemillis (); <br/> system. out. println ("application time consumed" + (endtime-begintime) + "millisecond"); <br/>}</P> <p >}< br/>
The running result is as follows:
I = 0 <br/> I = 1 <br/> I = 2 <br/> I = 3 <br/> I = 4 <br/> I = 5 <br /> I = 6 <br/> I = 7 <br/> I = 8 <br/> I = 9 <br/> the application time is 10000 milliseconds. <br/> program exit Event Response <br/>