Java – after a period of time, let the thread go to the last

I have a thread that may get stuck and continue running Therefore, after a period of time, I want it to stop executing, go to the finally method to clean up, and then die How can I do this safely? thank you.

My first idea of how to do this is to make a sub thread, sleep and clean it up But when the parent thread is still trying to run, it cannot output an error

Solution

Refactor your code to callable and use executorservice to get the future Then use get timeout, and throw timeoutexception if there is no timeout For a complete example, see https://stackoverflow.com/a/2275596/53897.

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
分享
二维码
< <上一篇
下一篇>>