Interrupt an external method call in java Thread

血红的双手。 提交于 2019-12-01 15:02:42

There's not a whole lot you can do to stop that other method's progress, if it doesn't check the thread's interrupt bit or provide some other cancellation mechanism. Basically, a thread (ie, the methods that run on it) needs to cooperate with other threads if it's to be interrupted.

However, your program will end as soon as all non-daemon threads finish. So if you don't want that other thread to block the exiting progress, all you need to do is to call thread.setDaemon(true) before you start() the thread. Then your daemon threads (including the one that main ran in) can finish whatever cleanup they need to do, and your program will exit without waiting for that daemon thread to finish.

EDIT: This answer originally talked about using Futures, missing the OP's point that this is for the special case of the program exiting. See this answer's history if you want to read about Futures.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!