Skip to content
Advertisement

Call to method with a thread inside implies a wait?

I have a method that writes a file and it can be a bit slow. So I did this to avoid blocking the rest of actions:

JavaScript

However it still takes a while until things B are executed after things A and I was wondering if I should do this instead:

JavaScript

Or, in other words, does calling a method with a thread inside it imply waiting for the method to end, and therefore the thread?

Just to clarify things: I want to know if both options would be the same or if in the first option the thread should finish for the B instructions to start.

Advertisement

Answer

Does calling a method with a thread on it imply waiting for the method to end, and therefore the thread?

No. To highlight that the thread isn’t a factor, I took your original code:

JavaScript

And sprinkled a bunch of System.out.println() calls throughout:

  • one before calling method(), and one right after
  • one at the start of method(), and one at the end
  • one at the start of the thread body, and one at the end

Also:

  • the thread does “slow stuff” by calling Thread.sleep() for 2 seconds
  • each println() includes current date+time
  • the output is crudely formatted with indentation to show the start/end pairs of each output
JavaScript

Output below, which shows a few things:

  • the first+second output lines in main (before and after calling method()) are basically instantaneous – 09:10:22.036305 start, 09:10:22.037957 end, for a difference of 0.001652 seconds
  • same for method(), nearly instantaneous with start of 09:10:22.037564 and end of 09:10:22.037897, which is a difference of 0.000333 seconds
  • the start and finish outputs in thread are where the waiting is, starting at 09:10:22.037920, ending at 09:10:24.041840; total difference of 2.00392 seconds which is the 2 seconds we asked for with Thread.sleep() plus the tiny amount of execution time similar to the others (0.00392)
  • perhaps most importantly for this question, it’s clear that both the original caller (in main()) and method() both finish before thread finishes ~2 seconds later
JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement