Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 347
Mr.Noob Avatar asked Dec 12 '22 15:12

Mr.Noob


1 Answers

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.

like image 115
Gabe Sechan Avatar answered Dec 21 '22 09:12

Gabe Sechan