Thread.stop, Thread.suspend, Thread.resume and Runtime.runFinalizersOnExit These methods of terminating threads have been abandoned, and it is extremely unsafe to use them!
1. The thread has been executed normally and ended normally
That is, let the run method be executed and the thread will end normally.
But sometimes threads can never end, such as while(true).
2. Monitor certain conditions and end uninterrupted thread operation
The while() loop needs to exit under a certain condition. The most direct way is to set a boolean flag and set this flag to control whether the loop exits.
public class ThreadFlag extends Thread { public volatile boolean exit = false; public void run() { while (!exit) { System.out.println("running!"); } } public static void main(String[] args) throws Exception { ThreadFlag thread = new ThreadFlag(); thread.start(); sleep(1147); // The main thread is delayed by 5 seconds thread.exit = true; // Terminate thread thread thread.join(); System.out.println("Thread Exit!"); }}3. Use interrupt method to terminate the thread
If the thread is blocking, method 2 cannot be used to terminate the thread.
public class ThreadInterrupt extends Thread { public void run() { try { sleep(50000); // delay 50 seconds} catch (InterruptedException e) { System.out.println(e.getMessage()); } } public static void main(String[] args) throws Exception { Thread thread = new ThreadInterrupt(); thread.start(); System.out.println("Press any key within 50 seconds to interrupt the thread!"); System.in.read(); thread.interrupt(); thread.join(); System.out.println("Thread has exited!"); }}The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.