Thread.stop,
Thread.suspend,
Thread.resumeAnd
Runtime.runFinalizersOnExitThese methods for terminating thread running have been discarded. using them is extremely insecure! To terminate a thread safely and effectively, use the following methods:
1. The thread runs normally and ends normally.That is to say, after the run method is executed, the thread will end normally.
2. monitor certain conditions to stop the uninterrupted running of the thread.However, some threads are often servo threads. They need to run for a long time. They can be closed only when some external conditions are met. Generally, they are executed in an infinite loop while (true. For example, @ override
Public VoidRun (){
While(
True) {Somework ();
If(Finished ){
Break;}
Try{Thread.
Sleep(10000 );}
Catch(Interruptedexception e ){/*
TodoAutomatically generate catch blocks **/E. printstacktrace () ;}}. We can check the external conditions during each loop in the while endless loop to see if the current thread needs to be closed. If yes, just break, jump out of the endless loop, or throw an exception, jump out of the endless loop, and end the thread.
3. CaptureInterruptedException The current thread is interrupted due to an exception during running. Some threads that execute servo tasks are blocked in an endless loop like while (true. In this case, the second method cannot be used. Because, when this method does not return, the thread remains in the blocking state and cannot execute other statements at all. In this case, you need to callInterrupt method to generate
Interruptedexception: An exception occurs when the method in the blocking operation throws this exception, giving us the opportunity to end the execution of this thread.For example, @ override
Public VoidRun (){
While(
True){
Try{// Getsendmessages is the blockingqueue class. Its take method will be blocked! Responsemessage =
This. Getsendmessages (). Take ();}
Catch(Interruptedexception E1 ){
Throw NewRuntimeexception (); // or break ;}
Somework ();} an external thread object points to this thread. To end this thread, you only need to call
Interrupt() Method, it will be in responsemessage =
This. Getsendmessages (). Take (); in this statement, an interruptedexception exception is generated to end the blocking status of the thread. By throwing an exception or breaking out of the dead loop, the thread is terminated.