java线程中方法调用,中断Java线程中的外部方法调用

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?

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值