Introduction to safe thread exit method of Java multithreaded programming

Thread stop

Thread provides a stop () method, but the stop () method is an obsolete method. Why is the stop () method abandoned instead of being used? The reason is that the stop () method is too violent and will forcibly terminate half of the thread. This will not guarantee the correct resource release of the thread. Usually, the thread is not given the opportunity to complete the resource release work, so the program will work in an uncertain state

What should we use to stop the thread

Thread. Interrupt(), we can use it to stop the thread. It's safe, but it won't really stop the thread when using it. It just marks the thread. What's the use of this mark? We can use it like this.

Although this will stop, the statements after for will still be executed.

Exception method exit thread

Explain that if we mark a mark, we can detect that it has been marked, and return a true. If we enter the if, an exception is returned, which will terminate. This allows threads to stop within our control

How to see what state

this. Interrupted (): check whether the current thread is in an interrupted state. After execution, the state representation is changed to false this Isinterrupted (): check whether the thread object is already in the interrupt state, but do not clear the interrupt state flag.

summary

The above is all about the safe thread exit method of Java multithreaded programming in this paper. I hope it will be helpful to you. Interested friends can continue to refer to this site: talking about the wonderful use of future in Java multithreading (with source code), detailed explanation of Java multithreading forkjoinpool instance, etc. if you have any questions, you can leave a message at any time, and the Xiaobian will reply to you in time. The following two books on Java programming are recommended for reference:

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>