Interrupt an external method call in java Thread

2019-02-21 04:00发布

问题:

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.