Part 5 add exit events to the program

Source: Internet
Author: User

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/>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.