Saturday, 10 June 2017

Java Tutorial: Java Runtime class (shutdown hook_V1) ~ foundjava


Click here to watch in Youtube :

Click the below Image to Enlarge
Java Tutorial: Java Runtime class (shutdown hook_V1) 
Java Tutorial: Java Runtime class (shutdown hook_V1) 
ShudownHookThread.java
public class ShudownHookThread extends Thread
{

    public void run()
    {
        System.out.println("Shut down hook task is completed..");
    }
}
ShutdownHookDemo.java
/*
 * public void addShutdownHook(Thread hook)
 * 
 * Parameters: 
 * ----------- 
 * 
 * hook - An initialized but unstarted Thread object
 */
public class ShutdownHookDemo
{
    public static void main(String[] args)
    {
        /*
         * Returns the runtime object associated with the
         * current Java application.
         */
        Runtime runtime = Runtime.getRuntime();
        /*
         * Registers a new virtual-machine shutdown hook.
         */
        runtime.addShutdownHook(new ShudownHookThread());

        System.out.println("Now main thread sleeping... press ctrl+c to exit");

        try
        {
            Thread.sleep(5000);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

    }

}
Output
Now main thread sleeping... press ctrl+c to exit
Shut down hook task is completed..
AnnonymousShutdownHook.java
public class AnnonymousShutdownHook
{

    public static void main(String[] args)
    {
        Runtime runtime = Runtime.getRuntime();

        runtime.addShutdownHook(new Thread()
        {
            public void run()
            {
                System.out.println("Shut down hook task is completed..");
            }
        });

        System.out.println("Now main thread sleeping... press ctrl+c to exit");
        try
        {
            Thread.sleep(5000);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

}
Output
Now main thread sleeping... press ctrl+c to exit
Shut down hook task is completed.

Refer: 
https://docs.oracle.com/javase/8/docs/api/index.html?java/lang/Runtime.html
Click the below link to download the code:

CLICK HERE

No comments:

Post a Comment