1, simple to understand: Why do not agree with the use of Thread.stop, Thread.Suspend and Thread.Resume?
?? The suspend, resume, and stop methods are used to suspend, resume, and terminate the threads respectively. The reason for this is not recommended: Because of the side effects of these three methods, such as the Suspend () method, the thread will always take up resource sleep until resume () is called, before it can be run. This can easily cause deadlocks. Similarly, the Stop () method does not guarantee that a thread's resources are properly freed when it ends a thread, and therefore causes the program to work in an indeterminate state.
?? The Suspend/resume operation of a thread can be replaced by a wait/notification mechanism. But the termination of the thread will be implemented by the user.
For more information, refer to: http://bjzhkuang.iteye.com/blog/1748396
2. How to gracefully and safely terminate a thread
?? Terminating a thread is essentially a process of communication interaction between threads. Therefore, the way of communication between threads: Shared variables, streams, interrupts can be used to implement the mechanism of terminating the thread. The most common way is "interruption";
The following example is: In addition to interrupts, a Boolean variable can be used to control whether the thread needs to be terminated;
Public classthreadtest{ Public Static void Main(string[] args)throwsinterruptedexception {MyTask TaskOne =New MyTask(); Thread Threadone =NewThread (TaskOne,"Threadone"); Threadone.Start(); Timeunit.MILLISECONDS.Sleep( -); Threadone.Interrupt(); MyTask Tasktwo =New MyTask(); Thread Threadtwo =NewThread (Tasktwo,"Threadtwo"); Threadtwo.Start(); Timeunit.MILLISECONDS.Sleep( -); Tasktwo.Cancel();}Private Static classMyTaskImplementsrunnable{//To add the volatile modifier to ensure the visibility of the memory, update the value of the variable in time Private volatile BooleanOn =true;Private LongI@Override Public void Run() {//Call Cancel, or interrupt to terminate the thread while(On &&!) Thread.CurrentThread().isinterrupted()) {i++; } System. out.println("Threads"+thread.CurrentThread().GetName()+"Count i ="+i); } Public void Cancel() {on =false; } }}
Operation Result:
Thread Threadone Count i = 239418320
Thread Threadtwo Count i = 235374425
Concurrency basis (ix) termination and interruption of Java threads