开发者

Stop a thread after period of time

开发者 https://www.devze.com 2023-04-09 01:06 出处:网络
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).

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  = ne开发者_如何学Pythonw 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?

  1. 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".
  2. 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 Locks because I bet there can be some race condition.

Cheers.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号