How to kill a thread in android?

I have a background thread running in my application and I need to kill it safely. How can I kill a thread in java besides using a boolean flag? I read that I can no longer use thread.stop () since it is unsafe. but is there a way to do this? can someone give me a code snippet for this please?

thanks

+4
source share
3 answers

It is never safe in any language to kill a thread - you do not know what this thread can do and what state it can leave. Using the undo method with a thread that periodically checks isCanceled allows the thread to control its own security — it can only do this when it would be safe to kill itself or do the necessary cleanup.

If you really don't need to kill the thread, but just want to wait until it is finished, use join.

If you absolutely need to kill the thread, continue and use stop. Just don't expect your state to be safe or consistent after that - it really should only be done when the application / activity terminates.

+8
source

Try using something like

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

Or

 thread.interrupt(); thread = null; 
+5
source

You need to use the flag. For example:

 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. } 
0
source

Source: https://habr.com/ru/post/1481797/


All Articles