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. 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 th开发者_开发问答read process is not completed in 1 min. 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.
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.
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. In particular, the cancel(boolean) method can be used to interrupt the task if it has started but not finished.
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.
you can use the method : Thread.interrupt();
the method Thread.stop() is deprecated
Create a stop method like this, and call interrupt subsequently.
public void stop() {
Thread currentThread= someThread;
someThread= null;
currentThread.interrupt();
}
精彩评论