1

I want execute Thread when main Thread release resources.

I have main Thread

Thread mainThread = new Thread(() -> {
    //do things
    doAction();
    //do other things
});

and method doAction() looks like

public void doAction(){
   Thread insideThread = new Thread(() -> {
      //do something
   });

   insideThread.start();
}

Now it looks that the insideThread is executed while mainThread is running.

What happens to insideThread when mainThread dies or is released?

I want start insideThread at the moment when mainThread dies or released.

ACz
  • 567
  • 5
  • 22

1 Answers1

3

Simple solution: change doAction() to return that thread it is creating; so that the calling code can call start() on that Thread; like this:

public Thread doAction(){
  Thread insideThread = new Thread(() -> {
    //do something
  });

  return insideThread;
}

Of course, you would then rename that method to something like prepareAction() to indicate that it doesn't "do" things itself.

Edit: this is one option to implement your requirement; but the core thing is: no matter if that method returns a value; or (for example) sets some field - the point is: if you want to control a thread T from within another thread M, than M needs a reference to that T. There is no magic here, any object can only "manage" other objects that are somehow known to it!

GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • I do like this answer because the code could predate Tasks, but I would suggest adding an async/await and Tasks example as well since it's the more modern approach to said thing. – HouseCat Jan 11 '17 at 13:59
  • @RagingCain Thank you; sounds like a good idea; but not sure if I get there today.Feel free to edit and improve my answer. Now I am wondering if mentioning that I am a grateful upvoter would look like attempted bribery ;-) – GhostCat Jan 11 '17 at 14:14