Mr.Noob
Mr.Noob

Reputation: 1005

How to kill a thread in android?

I've got a background thread running in my application and I need to kill it safely. How can I kill a thread in java other than using a boolean flag? I have read that i cannot use thread.stop() anymore as it is not safe. but is there a proper way of doing this? can someone give me a code snippet for it please?

Thanks

Upvotes: 4

Views: 11510

Answers (3)

quangnhat008
quangnhat008

Reputation: 1

You need using flag. For ex:

private boolean isThOn; //flag isThOn
long delaytime;
int times;
...
new Thread() {
        public void run() {
            int i=0;
            isThOn = true;
            while (isThOn && i<times) {
                try {
                    i++;
                    //{...}
                    if (i == times) isThOn = false;
                    sleep(delaytime);
                } catch (Exception e) {e.printStackTrace();}
            }
        }
}.start();
public void cancelthd() {
    isThOn = false; //whileloop will stop if isThOn = false -> Thread will Terminated befor i = times.
}

Upvotes: 0

chuckliddell0
chuckliddell0

Reputation: 2061

Try using something like

service.getThread().interrupt();
service.setThread(null);

Or

thread.interrupt();
thread = null;

Upvotes: 5

Gabe Sechan
Gabe Sechan

Reputation: 93561

Its never safe in any language to kill a thread- you don't know what that thread may be doing and what state it may leave behind. Using the cancel method with the thread occassionally checking isCanceled allows the thread to manage its own safety- it can choose to do this only when it would be safe to kill itself or to do the needed cleanup.

If you don't actually need to kill a thread but just want to wait until its over, use join.

If you absolutely need to kill a thread, go ahead and use stop. Just don't expect your state to be safe or consistent afterwards- this should really only be done when terminating the application/activity.

Upvotes: 8

Related Questions