中断Java线程中的外部方法调用 [英] Interrupt an external method call in java Thread

查看:183
本文介绍了中断Java线程中的外部方法调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Java程序使用需要一段时间才能完成的外部方法(我没有源代码),因此我在Thread类(在其run方法中)中对该方法进行了调用.现在的问题是,如果用户要退出程序,如何立即停止线程(不等待方法结束).

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.

但是,您的程序将在所有非守护程序线程结束后立即结束.因此,如果您不希望其他线程阻止正在退出的进程,那么您要做的就是在start()线程之前调用thread.setDaemon(true).这样,您的守护程序线程(包括运行main的守护程序线程)就可以完成所需的清理工作,并且您的程序将退出而无需等待该守护程序线程完成.

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.

编辑:该答案最初是关于使用Future的,而忽略了OP的观点,即这是针对程序退出的特殊情况.如果您想阅读有关Future s的信息,请参阅此答案的历史记录.

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.

这篇关于中断Java线程中的外部方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆