[Solved] What is the use of join(long milliseconds) over sleep(long milliseconds) in Thread [duplicate]


Assuming you have one thread: use sleep(timeout) – it will always wait timeout seconds before continuing.

Assuming you have two threads:

  • Option 1: Thread1 simply should wait and has nothing to do with Thread2 – use sleep(timeout) – it will always wait timeout seconds before continuing.
  • Option 2: Thread1 does have something to do with Thread2 and therefore (and only therefore) calls join(timeout) on Thread2.
    • Option 2.1: Thread2 finishes before the timeout. Thread1 can immediately continue its processing knowing that Thread2 has completed. It will not wait as many as timeout seconds.
    • Option 2.2: Thread2 finishes after the timeout. Thread1 now knows that Thread2 is still doing some work and can maybe show the user “the process is taking a bit longer” or even cancel the other task. At this point it will waited timeout seconds. This behaves like sleep but you do not know beforehand wether 2.1 or 2.2 will happen, therefore sleep is not a proper alternative.

solved What is the use of join(long milliseconds) over sleep(long milliseconds) in Thread [duplicate]