Runtime.addshutdownhook Add Hooks

Source: Internet
Author: User
1 Method meaning
The void Java.lang.Runtime.addShutdownHook (Thread hook) is used to add a closed hook in the JVM.
When the program exits normally, the added Shutdownhook thread is executed when the system calls the System.exit method or when the virtual machine is shut down. Where Shutdownhook is an initialized thread that does not start, and when the JVM shuts down executes all hooks that have been set up in the system by means of Addshutdownhook, and the JVM shuts down when the system finishes executing the hooks. These hooks can be used for memory cleanup, resource recycling, and so on when the JVM shuts down.


2 Sample Code
public class Testruntimeshutdownhook {
public static void Main (string[] args) {

thread shutdownhookone = new Thread () {
public void Run () {
System.out.println ("Shutdownhook one ...");
}
};
Runtime.getruntime (). Addshutdownhook (Shutdownhookone);


Runnable Threadone = new Runnable () {

public void Run () {
try {
Thread.Sleep (1000);
catch (Interruptedexception e) {
E.printstacktrace ();
}
SYSTEM.OUT.PRINTLN ("Thread one doing something ...");
}
};


Runnable threadtwo = new Thread () {
public void Run () {
try {
Thread.Sleep (2000);
catch (Interruptedexception e) {
E.printstacktrace ();
}
SYSTEM.OUT.PRINTLN ("Thread two doing something ...");
}
};


Threadone.run ();
Threadtwo.run ();
}
}

The output is as follows:
Thread one doing something ...
Thread two doing something ...
Shutdownhook one ...


Original posted Address: http://kim-miao.iteye.com/blog/1662550

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.