Home >Java >javaTutorial >How to stop terminating thread in Java?
There are four ways to stop and terminate a thread in Java: interrupt() method: interrupt the thread and throw an InterruptedException exception. stop() method: Not recommended as it stops the thread immediately, possibly resulting in data loss. Set interrupt flag: Set a flag for the thread to poll to determine whether it needs to be terminated. Using join(): Blocks the current thread until the thread calling join() from another thread terminates.
In Java, threads can be terminated in many ways. Understanding how to properly terminate threads is critical to ensuring application stability and performance. This article will discuss common methods of stopping and terminating threads, with practical cases attached.
interrupt()
method can be used to interrupt the execution of a thread. If the thread is sleeping or waiting for I/O, you will receive an InterruptedException
exception. In the following practical case, we use the interrupt()
method to stop a sleeping thread:
public class InterruptThreadExample { public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(() -> { try { Thread.sleep(10000); // 睡 10 秒 } catch (InterruptedException e) { System.out.println("已中断!"); } }); thread.start(); Thread.sleep(1000); // 睡 1 秒 thread.interrupt(); thread.join(); // 等待线程终止 } }
Output:
已中断!
The stop() method is not recommended because it stops the thread immediately, possibly causing data loss or application instability. It is strongly recommended to use the interrupt()
method instead.
You can set an interrupt flag for threads to poll. When this flag is set to true, the thread knows that it should terminate:
public class InterruptFlagExample { private volatile boolean interrupted = false; public static void main(String[] args) throws InterruptedException { InterruptFlagExample example = new InterruptFlagExample(); Thread thread = new Thread(() -> { while (!example.isInterrupted()) { // 做一些事情 } }); thread.start(); Thread.sleep(1000); // 睡 1 秒 example.setInterrupted(true); thread.join(); // 等待线程终止 } public void setInterrupted(boolean interrupted) { this.interrupted = interrupted; } public boolean isInterrupted() { return interrupted; } }
join()
method can be used to stop and wait for the thread to terminate . It will block the current thread until another thread that calls join()
terminates.
public class JoinExample { public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(() -> { try { Thread.sleep(10000); // 睡 10 秒 } catch (InterruptedException e) {} }); thread.start(); thread.join(); // 等待线程终止 } }
This blocks the current thread for 10 seconds until the other thread terminates.
The above is the detailed content of How to stop terminating thread in Java?. For more information, please follow other related articles on the PHP Chinese website!