Reputation: 53826
How can I stop a thread running after it has been running for 5 seconds ?
I am unable to use java 5+ threading features (must work in j2me).
Possible solution -
Schedule two threads. One which performs the actual work(T1) and the other which acts as monitor of T1(T2).
Once T1 has started then start T2. T2 calls the isalive() method on T1 every second and if after 10 seconds T2 has not died then T2 invokes an abort on T1, which kills the T1 thread.
is this viable ?
Timer timer = new Timer();
TimerTask timerTask = new TimerTask() {
public void run() {
getPostData();
}
};
timer.schedule(timerTask, 0);
public void abortNow() {
try {
_httpConnection.close();
}
catch(Exception e){
e.printStackTrace();
}
}
Upvotes: 2
Views: 10421
Reputation: 11403
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?
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".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.
Upvotes: 1