Stop Thread Immediately

I want to stop the current thread immediately. Here is my code:

Grade A:

public class A() {
    public void methodA() {
        For (int n=0;n<100;n++) {
        //Do something recursive
        }
        //Another for-loop here

        //A resursive method here

        //Another for-loop here

        finishingMethod();        
    }    
}

Grade B:

public class B() {
    public void runEverything() {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                    A a = new A();
                    a.methodA();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
       Thread thread = new Thread(runnable);
       thread.start();
    }

My problem is that I need to be able to stop the thread in class B before the thread finishes. I tried the interrupt () method, but that does not stop my thread. I also heard about using a shared variable as a signal to stop my thread, but I think that with a long recursive and for-loop in my process, shared-variable will not be effective.

Any idea? Thanks in advance.

+5
source share
4 answers

Thread.interrupt ( , InterruptedException). , , , .

, , , . methodA , , - :

// this is a new instance variable in `A`
private volatile boolean cancelled = false;

// this is part of your methodA
for (int n=0;n<100;n++) {
  if ( cancelled ) {
    return; // or handle this however you want
  }    
}

// each of your other loops should work the same way

public void cancel() {
  cancelled = true;   
}

, - runEverything on B, B cancel A ( A, B runEverything.

+11

, Thread.interrupt(). , methodA, - :

public void methodA() throws InterruptedException {
    for (int n=0; n < 100; n++) {
        if (Thread.interrupted) {
             throw new InterruptedException();
        }
        //Do something recursive
    }
    // and so on.        
}

"kill switch", , :

  • API- , API- - interrupted
  • interrupted.

, mishandles InterruptedException; . ( InterruptedException , Thread.interrupt(), .) , kill, , .

+2

. kill (.. false), ( , ).

+1

:

1) - , "", "" , . , , .

2) Discard, ruin, rename, close, or otherwise destroy the data it is working on to force the segfault / AV stream or otherwise. A thread can catch a throw and check the Abort flag.

No warranties sold, as you can see ...

0
source

All Articles