Thursday, 9 February 2017

Java Tutorial: Java Threads (Interrupting a Thread | Java thread interrupt)


Click here to watch in Youtube :
https://www.youtube.com/watch?v=jI284uQU5p0&list=UUhwKlOVR041tngjerWxVccw

Click the below Image to Enlarge
Java Tutorial: Java Threads (Interrupting a Thread | Java thread interrupt) 
Java Tutorial: Java Threads (Interrupting a Thread | Java thread interrupt) 
DisplayThread.java
/*
 * Example of interrupting a thread that stops
 * working.
 * 
 * In this example, after interrupting the thread, we
 * are propagating it, so it will stop working. If we
 * don't want to stop the thread, we can handle it where
 * sleep() or wait() method is invoked.
 */
class DisplayThread extends Thread
{

    public static void main(String args[])
    {
        DisplayThread t1 = new DisplayThread();
        t1.start();
        try
        {
            t1.interrupt();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

    }

    public void run()
    {
        try
        {
            System.out.println("Going to sleep...");
            Thread.sleep(1000);
            System.out.println("Welcome to India...");
        }
        catch (InterruptedException e)
        {
            throw new RuntimeException("Thread interrupted... " + e);
        }

    }

}
Output
Exception in thread "Thread-0" Going to sleep...
java.lang.RuntimeException: Thread interrupted... 
java.lang.InterruptedException: sleep interrupted
    at DisplayThread.run(DisplayThread.java:38)

Click the below link to download the code:
https://sites.google.com/site/ramj2eev1/home/javabasics/ThreadDemo_Interrupting_Thread_App.zip?attredirects=0&d=1

Github Link:
https://github.com/ramram43210/Java/tree/master/BasicJava/ThreadDemo_Interrupting_Thread_App

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/644abf74fceeb240066dd3d2fe2e4b1fb6c4bd48/BasicJava/ThreadDemo_Interrupting_Thread_App/?at=master

See also:

  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • No comments:

    Post a Comment