简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM