Interrupt an external method call in java Thread

僤鯓⒐⒋嵵緔 提交于 2019-12-01 12:37:40

问题


My java program use an external method(i dont have the source code) that takes a while to finish so i have made the call to that method in a Thread class (in its run method). Now the problem is how do I stop the Thread instantly (not wait for the method to end) if user wants to exit program.

When I call my Thread's interrupt method nothing happens, no interrupted exception before the external method is finished. I thought an interrupted exception could occur and be caught at the same time that the external method is running but maybe not?

I'm not sure how about how Threads works exactly. So how do you solve this?


回答1:


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.



来源:https://stackoverflow.com/questions/21270196/interrupt-an-external-method-call-in-java-thread

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