Friday 20 January 2017

Java Tutorial: Java Threads (Java thread interrupt | How to interrupt the thread)


MyRunnable.java
public class MyRunnable implements Runnable
{

    Thread t;

    public MyRunnable()
    {

        t = new Thread(this);
        System.out.println("Executing " + t.getName());
        // this will call run() fucntion
        t.start();

        /*
         * Tests whether the current thread has been
         * interrupted.
         */
        if (!t.interrupted())
        {
            // Interrupts this thread.
            t.interrupt();
        }
        // block until other threads finish
        try
        {
            t.join();
        }
        catch (InterruptedException e)
        {
        }
    }

    public void run()
    {
        try
        {
            while (true)
            {
                Thread.sleep(1000);
            }
        }
        catch (InterruptedException e)
        {
            System.out.println(t.getName() + " interrupted:");
            System.out.println(e.toString() + "\n");
        }
    }
}
ThreadDemo.java
public class ThreadDemo
{

    public static void main(String args[])
    {
        new MyRunnable();
        new MyRunnable();
    }
}
Output
Executing Thread-0
Thread-0 interrupted:
java.lang.InterruptedException: sleep interrupted

Executing Thread-1
Thread-1 interrupted:
java.lang.InterruptedException: sleep interrupted

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

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

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/4a03b5014bb513b61dfa414428ea9747b1421899/BasicJava/ThreadDemo_interrupt_how_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