Võ Khắc Bảo
Võ Khắc Bảo

Reputation: 53

Stop thread in Java multithreading

I ran into a small problem during my self-study, which was using "interrupt" to interrupt the "StopThread" thread. I have created a simple program that asks to print "Thread is running" line in a while loop and repeats after 1 second until receiving interrupt signal from main thread which will print "Thread stopped. ..". However, when the main thread calls the interrupt signal, the StopThread thread does not interrupt the program, the thread throws an InterruptException, and the while() loop continues to be started. I know another method to get around this is to use the boolean interrupt flag, but here I just want to achieve the goal by using "interrupt". Any suggestions or sample code for me? I would be very grateful for that. I'm a newbie to multithreaded Java. Thank you very much.

class StopThread extends Thread {
@Override
public void run() {
    while (!Thread.interrupted()) {
        System.out.println("Thread is running....");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
    System.out.println("Thread Stopped.... ");

}
}

public class Test2 {
public static void main(String args[]) {

    StopThread thread = new StopThread();

    thread.start();

    try {
        Thread.sleep(5000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    thread.interrupt();
} 
}

Upvotes: 1

Views: 81

Answers (1)

Nathan Hughes
Nathan Hughes

Reputation: 96444

When an InterruptedException is thrown the interrupt flag gets reset. Your catch block needs to call

Thread.currentThread().interrupt()

to set the flag again.

I have a code example of using interrupt here https://stackoverflow.com/a/5097597/217324. The example uses isInterrupted instead of interrupted, because interrupted clears the flag, but that's not what causes your problem.

Upvotes: 2

Related Questions