1

I'm using the method from the accepted answer here to construct a gameloop thread.

Where to stop/destroy threads in Android Service class?

At the moment, my thread basically gets the time, makes a single Native Function call that updates the game logic, then sleeps by the adjusted passed time.

What I'm curious of, since I'm still not very comfortable with Threads, is how fast a Thread is killed with interrupt()? If it is in the middle of the code running in the Native Function, will it stop in the middle of it, or will it safely complete?

Thanks ahead of time, Jeremiah

Community
  • 1
  • 1
Maximus
  • 8,351
  • 3
  • 29
  • 37

1 Answers1

3

No worries, the documentation for interrupt says:

If this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.

So your thread will only get the InterruptedException if you're in some type of blocking/sleeping/waiting state. If you're running, the thread will not get the exception until it enters one of those states.

Your loop should be:

while(!Thread.currentThread().isInterrupted()) // <- something of the sort here
{
    try{
        // do work
    } catch (InterruptedException e){
        // clean up
    }
}

Update:
Additionally, the documentation states:

If none of the previous conditions hold then this thread's interrupt status will be set.

Sebastian S
  • 4,420
  • 4
  • 34
  • 63
Kiril
  • 39,672
  • 31
  • 167
  • 226
  • But if it is not blocked by one of those methods, say calling the native method... does it simply stop? – Maximus Jun 16 '11 at 21:02
  • 1
    @Maximus, no it doesn't stop... only the `isInterrupted` state is set, so you have to check the state every time you loop through. – Kiril Jun 16 '11 at 21:09