Stop and restart a thread inside itself

I have a thread implemented inside a class using runnable, like this:

static Runnable myThread = new Runnable() { public void run(){ try{ //do something forever }catch(Exception e){ //something happened. Re-run this thread } } } 

I want to continue working with this thread, even if an exception is detected. So how can I do this in an exception clause? Is there a more elegant solution for this?

+4
source share
2 answers

Use a loop:

 static Runnable myThread = new Runnable() { public void run() { for (;;) { try { ... } catch(Exception e) { ... } } } } 

Whatever you do, I would strongly recommend that you silently ignore the exception. If there is no better way to handle the exception, at least register it.

+6
source

You can do this after a while and continue the cycle. Sort of:

 public void run() { while (true) try { // do something forever } catch(Exception e) { // something happened. Re-run this thread continue; } ... } } 
+3
source

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


All Articles