How to stop a thread with a thread interrupt method

I am trying to find out if a thread is interrupted and how to terminate a thread without calling stop.

public class Test implements Runnable{
        static Thread threadTest=null;
        public static void main(String args[]){
          System.out.println("Hello i am main thread");
          Test thread= new Test();
          threadTest= new Thread(thread);
          threadTest.start();   
}

private static void exitThread() {
    threadTest.interrupt();
}

 @Override
 public void run() {
    boolean run = true;
    while (run) {
        try {
            System.out.println("Sleeping");
            Thread.sleep((long) 10000);
            exitThread();
            System.out.println("Processing");

        } catch (InterruptedException e) {

            run = false;
        }
    }

}


}

      

Output

Hello i am main thread

Sleeping

Processing

Sleeping

      

I can't figure out why Sleeping is being printed a second time, and the interrupted exception is thrown a second time, not the first time. I have checked posts where the volatile keyword is used to stop a thread in java.but, I cannot figure out how this would be used in this scenario since the thread is being interrupted with interruption.

+3


source to share


3 answers


To see the thread being interrupted instead of re-entering the sleep method, modify the while loop test in the run method to check the interrupt flag:

@Override
 public void run() {
    while (!Thread.currentThread().isInterrupted()) {
        try {
            System.out.println("Sleeping");
            Thread.sleep((long) 10000);
            exitThread();
            System.out.println("Processing");
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}

      

The thread will sleep and then set its own interrupt flag, then check the flag and exit. InterruptedException will be thrown out by the sleep # Thread method only if the thread slept while the interrupt flag was set.



A local boolean variable is not needed. If Thread # sleep throws InterruptedException (which will not be in this example, because the thread checks the interrupted flag and exits the while loop), the interrupt flag is cleared, restoring it in the catch block allows the test to check that the thread was interrupted.

In real programs, the thread will be interrupted from another thread, there is no reason to interrupt the thread (it may just come back instead).

+3


source


Calling Thread.interrupt () simply sets a flag for the thread. He does not do anything. Only blocking methods (usually throwing InterruptedException) respond (by throwing) this flag. The flag is sticky in that it remains set until it is cleared.

So, the first call to the hibernate method is fine (the interrupted flag is not set yet). After that, your code does nothing that affects the interrupted status, until the second iteration of the loop, when the sleep call detects the interrupted status and throws an exception.



You can use Thread.interrupted () or Thread.isInterrupted () to check for interrupted status at any time (beware that interrupted () also clears the interrupted status if it was set).

+1


source


here you create another Test class , but "main" has its own thread, so the new thread you created is interpreted. Here in this code you interrupt the created thread Thread-0 not the main thread, when you execute this code you create a thread to sleep before it enters the exitThread () method , so it displays the processing, but if you try to set the sleep thread after entering exitthread () , you get a response Like this code:

The public class Test implements Runnable {public boolean run = true;

@Override
public void run() {
    while (run) {

        try {
            System.out.println("Sleeping...");
            exitThread();
            Thread.sleep(10000);
            System.out.println("Processing...");
        } catch (InterruptedException e) {
            System.out.println("Thread intreputted " + e);
            run = false;
        }
    }
}

private void exitThread() {
    Thread.currentThread().interrupt();
    if (Thread.currentThread().isInterrupted())
        System.out.println(Thread.currentThread().getName()
                + " is intreputted");
    else
        System.out.println("alive");
}

public static void main(String[] args) {
    System.out.println("hi I am current thread------>"
            + Thread.currentThread().getName());
    Test test = new Test();
    Thread thread = new Thread(test);
    thread.start();
}

      

}

Hope this is helpful

+1


source







All Articles