Stopping thread Immediately

Viewed 10068

I want to stop a running thread immediately. Here is my code:

Class 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();        
    }    
}

Class 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 even before the thread is finished. I've tried interrupt() method, but that doesn't stop my thread. I've also heard about using shared variable as a signal to stop my thread, but I think with long recursive and for-loop in my process, shared-variable will not be effective.

Any idea ? Thanks in advance.

5 Answers

From main thread letsvsay someTask() is called and t1.interrput is being called..

t1.interrupt();

    }

    private static Runnable someTask(){
        return ()->{



            while(running){
                try {
                    if(Thread.interrupted()){
                        throw new InterruptedException(  );
                    }
               // System.out.println(i + " the current thread is "+Thread.currentThread().getName());


                  //  Thread.sleep( 2000 );
                } catch (Exception e) {

                    System.out.println(" the thread is interrputed "+Thread.currentThread().getName());
                    e.printStackTrace();
                    break;
                }
            }

o/P:

java.lang.InterruptedException
    at com.barcap.test.Threading.interrupt.ThreadT2Interrupt.lambda$someTask$0(ThreadT2Interrupt.java:32)
    at java.lang.Thread.run(Thread.java:748)
 the thread is interrputed Thread-0

Only t1.interuuption will not be enough .this need check the status of Thread.interrupted() in child thread.

Related