1

I wanted to ask if it is possible for a thread to end itself. I have a method in an instance of a thread that checks if an int Overflows but its not the run() method. I want to stop the thread if the internalSteps reach Integer.MAX_VALUE / numberOfAllThreads

    private void addInternalStep() {
    ++internalSteps;
    if( internalSteps == (Integer.MAX_VALUE / numberOfAllThreads) ) {
        System.out.println("Thread stopped. In danger of overflow.");
        this.interrupt(); // Not stopping the thread
    }
}

@Override
public void run() {

    while( !isInterrupted() ) {

            if(Math.pow(Math.random(), 2) + Math.pow(Math.random(), 2) < 1) {
                hits = hits.add(BigDecimal.ONE);
            }
            counter = counter.add(BigDecimal.ONE);
            addInternalStep();
    }
}

Why isnt this.interrupt() working ? And how do I interrupt the thread in the instance of itsself ?

  • There's no point in a thread interrupting itself. Interruption is just a way of another thread indicating that it wants a thread to stop what it's doing; it's up to the interrupted thread to check for interruption, and stop itself. There's no point in a thread doing this to itself: it can just stop what it's doing anyway. – Andy Turner Apr 26 '20 at 18:23
  • Note that calling `this.interrupt()` is a sign that you're extending Thread, when you probably should be invoking `Thread(Runnable)` instead. Also bear in mind that a Thread isn't necessarily being run on itself (believe it or not): Thread implements Runnable, so you can actually pass a Thread to another Thread to run, and it's the "another thread" you should be interrupting. – Andy Turner Apr 26 '20 at 18:27

1 Answers1

1

Calling interrupt only sets a flag, it doesn’t have any other effect.

A thread can call interrupt on itself. This can happen when a thread catches an InterruptedException and wants to restore the flag that got cleared when the exception was thrown.

This usually looks something like:

try {
    Thread.sleep(1000L);
} catch (InterruptedException e) {
    Thread.currentThread().interrupt():
}

But this special case is about the only time it makes sense.

Using the currentThread method makes sure the interrupt call acts on the currently executing thread regardless of how the code is executed.

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276