简体   繁体   English

如何在 java 中的一段时间后停止线程?

[英]How to stop a thread after some time in java?

In my android app I am having a thread in which I fetch data from a web service.在我的 android 应用程序中,我有一个线程,我在其中从 web 服务获取数据。 So normally it works well, but sometimes if the connection is too slow it kind of hangs.所以通常它工作得很好,但有时如果连接太慢它会挂起。 So is there any way by which I can set some time say 1 min, and if the thread process is not completed in 1 min.那么有什么方法可以让我设置一些时间,比如 1 分钟,如果线程进程没有在 1 分钟内完成。 then I would like to stop this thread and display a message to the user that connection is weak/slow and try later.然后我想停止这个线程并向用户显示连接弱/慢的消息,然后再试。 Please help !!请帮忙 !!

This is a bad idea.这是一个坏主意。 The Thread.stop method is deprecated for good reasons.不推荐使用Thread.stop方法是有充分理由的。

I suggest you do the following: Set the network time-outs according to your preferences.我建议您执行以下操作: 根据您的喜好设置网络超时。 If this doesn't help, I suggest that you simply throw away the reference to the thread, (ignore it, let it die out and get garbage collected) and respond with a nice message about network failure.如果这没有帮助,我建议您简单地丢弃对线程的引用(忽略它,让它消失并收集垃圾)并以关于网络故障的好消息进行响应。 You can very well start a new thread for trying again.您可以很好地启动一个新线程以再次尝试。

you can use the method: Thread.interrupt();你可以使用方法: Thread.interrupt(); the method Thread.stop() is deprecated不推荐使用Thread.stop()方法

Create a stop method like this, and call interrupt subsequently.像这样创建一个停止方法,然后调用中断。

public void stop() {
    Thread currentThread= someThread;
    someThread= null;
    currentThread.interrupt();
}

I don't know whether it is supported in Android, but this is exactly what the Future objects returned from an ExecutorService are supposed to do for you.我不知道 Android 是否支持它,但这正是从ExecutorService返回的Future对象应该为您做的事情。 In particular, the cancel(boolean) method can be used to interrupt the task if it has started but not finished.特别是, cancel(boolean)方法可用于在任务已启动但尚未完成时中断该任务。

The tasks should be written to be aware that they may be interrupted, and abort cleanly if they have been.编写任务时应注意它们可能会被中断,如果已经中断,则干净地中止。 Most of the framework IO methods can be interrupted, so you just need to worry about your own code.大多数框架 IO 方法都可以被中断,所以你只需要担心你自己的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM