There is no unique answer to your question. It depends on what the thread does. First of all, how do you plan to stop that thread?
- If it elaborates some stuff, and this stuff is made of "tokens" such as single "tasks" to do, and the thread grabs them from a
BlockingQueue
for example, then you can stop the thread with a so-called "poison pill", like a mock task that the thread reads as: "Hey man, I have to shut down".
- If the thread does something which cannot be "divided" into "steps" then you should actually tell us how do you think it can be shut down. If it blocks on
read()
s on a socket, you can only close the socket to unblock it.
Please note interrupt()
is not meant to stop a Thread
in normal circumstances, and if you interrupt()
a thread, in most cases it'll just go on doing its stuff. In 99.9% of cases, it is just bad design to stop a thread with interrupt()
.
Anyway, to stop it after 5 seconds, just set a Timer
which does so. Or better join
it with a timeout of 5 seconds, and after that, stop it. Problem is "how" to stop it. So please tell me how do you think the thread should be stopped so that I can help you in better way.
Tell me what the thread does.
EDIT: in reply to your comment, just an example
class MyHTTPTransaction extends Thread {
public MyHTTPTransaction(.....) {
/* ... */
}
public void run() {
/* do the stuff with the connection */
}
public void abortNow() {
/* roughly close the connection ignoring exceptions */
}
}
and then
MyHTTPTransaction thread = new MyHTTPTransaction(.....);
thread.start();
thread.join(5000);
/* check if the thread has completed or is still hanging. If it's hanging: */
thread.abortNow();
/* else tell the user everything went fine */
:)
You can also set a Timer
, or use Condition
on Lock
s because I bet there can be some race condition.
Cheers.