Saturday, 10 June 2017

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


Click here to watch in Youtube:
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:

CLICK HERE

No comments:

Post a Comment