Case 1: Do stuff, then wait for results, then continue.
myThread.join()
is for cases when the code that created the thread does some more stuff after starting the thread, and then wants to wait for the thread's result. Once the thread's code is done, the thread dies, and thus the application continues execution after the join() call.
To give the application information from the thread, you'd have to store it somewhere, e.g. in a field dedicated for this. You don't have to worry about synchronization, because once the thread has died, all its actions will become "common knowledge", they are not privately timed (or whatever) any more.
Case 2: Keep doing stuff, and regularly check if results are available.
If instead your intention is to have some kind of game loop, where you keep doing stuff, and your extra thread is only meant to deliver some goods to you eventually (e.g. render a star background image while your game is already running), again you should hand it to the application in a field (aka class variable).
In that case, though, you have to worry about synchronization. Because as the game loop keeps checking if the field has changed from null
to a value, the two threads are racing each other.
So, in that case you'd need an extra object to synchronize on, ideally a dedicated one for this task, e.g. final private Object lockForBackgroundCalculation = new Object();
, and when the thread writes its result value into the other field, you wrap that statement into synchronized(lockForBackgroundCalculation){...}
, and you also wrap your game loop's checking of the field value into the very same sync block text.
Thread.join()
is used to wait for a thread to complete. A better solution is to use one of the classes fromjava.util.concurrent
. – markspace