Advertisement
//Java - Interrupting a running thread
class Intr implements Runnable //Implementing the Runnable interface
{
public void run() //Entry point of new thread
{
for(int i=0;i<5;i++)
{
System.out.println(i);
if (Thread.interrupted()) // Checking interrupt status
System.out.println("Thread was interrupted");
}
}
public static void main(String... ar)
{
Intr newTh= new Intr();
Thread th= new Thread(newTh,"Thread2"); //Calling Thread's constructor & passing the object
//of class that implemented Runnable interface
//& the name of new thread.
//Starts the thread
th.start();
//Interrupts the thread while it is running
th.interrupt();
}
}
0
Thread was interrupted
1
2
3
4
Advertisement
//Java - Manually throwing InterruptedException from a running thread.
class Intr implements Runnable //Implementing the Runnable interface
{
public void run() //Entry point of new thread
{
for(int i=0;i<5;i++)
{
System.out.println(i);
try
{
if (Thread.interrupted()) // Checking interrupt status of Thread2
throw new InterruptedException(); //throwing an InterruptedException manually.
}
catch(Exception e)
{
System.out.println(e);
}
}
}
public static void main(String... ar)
{
Intr newTh= new Intr();
Thread th= new Thread(newTh,"Thread2"); //Calling Thread's constructor & passing the object
//of class that implemented Runnable interface
//& the name of new thread.
//Starts the thread
th.start();
//Interrupts the thread while it is running, raising InterruptedException
th.interrupt();
}
}
0
java.lang.InterruptedException
1
2
3
4
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement