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();
}
}
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?
BlockingQueuefor 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 aThreadin normal circumstances, and if youinterrupt()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 withinterrupt().Anyway, to stop it after 5 seconds, just set a
Timerwhich does so. Or betterjoinit 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
and then
🙂
You can also set a
Timer, or useConditiononLocks because I bet there can be some race condition.Cheers.