This is purely a theoretical question as I'm not sure the conditions to cause this issue would be common.
Say for example you have a thread that you kick off with it's start method:
Thread c = new Thread();
c.start();
Then directly after, you call the Join() method on the thread to tell the method you are in to wait until the thread had been executed to continue.
c.join();
Isn't it a possibility that the thread could possibly be executed and finish before the join method is called, therefore leaving the method unaware that it had to wait for c to finish before it continued? I suppose you could try calling the join() method before you call the start() method, yet whenever I've tried this in test cases, there is an error.
Anyone know a possible fix for this, or does the JVM handle it? As I said I haven't been able to trigger this sort of situation, but theoretically it is possible...
Thread will continue to run (usually parallel with other threads) until it is either blocked by some synchronization operation or thread exits the its start function. The thread can wait with pthread_join() for other threads to finish execution successfully.
Join is a synchronization method that blocks the calling thread (that is, the thread that calls the method) until the thread whose Join method is called has completed. Use this method to ensure that a thread has been terminated. The caller will block indefinitely if the thread does not terminate.
join() does not do anything to thread t . The only thing it does is wait for thread t to terminate.
Thread class provides the join() method which allows one thread to wait until another thread completes its execution. If t is a Thread object whose thread is currently executing, then t. join() will make sure that t is terminated before the next instruction is executed by the program.
According to the Thread#join(long millis)
source code, the isAlive()
method is used to check the thread state.
/**
* Tests if this thread is alive. A thread is alive if it has
* been started and has not yet died.
*
* @return <code>true</code> if this thread is alive;
* <code>false</code> otherwise.
*/
public final native boolean isAlive();
This method obviously returns false
if the thread has finished, so thread.join()
will immediately exit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With