renderThread.interrupt() does not interrupt the thread, it continues
to run.
- If the thread is executing and
interrupt() is invoked it's interrupt status is set.
- If this thread is blocked in an invocation one of
wait methods of the Object class, or of the Thread.join and Thread.sleep methods of this class then its interrupt status will be cleared and it will receive an InterruptedException.
For example:
Thread t = new Thread()
{
public void run()
{
try {
for(int i=0; i<10000;i++)
System.out.println("Is interrupTed? "+this.isInterrupted());
Thread.sleep(200);
} catch (InterruptedException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
}
}
};
t.start();
t.interrupt();
}
The above code, I have used a for loop to intercept the interrput flag with isInterrupted() function and printed it. As t.interrupt() is invoked, isInterrupted() will return true which you will see in the console. As soon as it reaches the Thread.sleep(miliTime) you will see that InterruptedException is caught which was thrown as described above.
Stopping a thread:
you could make use of this isInterrupted() flag check if an interrupt() was invoked on it and return from the execution:
For example:
Thread t = new Thread()
{
public void run()
{
long executeTime = System.currentTimeMillis() ;
int i = 0;
for(; i<10000 && !this.isInterrupted();i++)
System.out.println("Is interrupted? "+this.isInterrupted());
System.out.println("Was Interrupted? "+this.isInterrupted()
+" after cycle: "+ i);
System.out.println("Time it gets Executed: "
+(System.currentTimeMillis() - executeTime+" ms"));
}
};
t.start();
try {
Thread.sleep(200);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
t.interrupt();
While running the above code: i have sent the main thread to sleep for 200 inside the static main function to allow the started thread t to run for some time. Then i invoked
t.interrupt() on it which causes the for loop to stop and print a output as following:
Was Interrupted? true after cycle: 1477
Time it gets Executed: 258 ms
Which indicates that the for loop has 1148 iteration before t.interrupt(); was invoked in the main function.
Please read the documentation of Thread.interrupt() function for more details.