You can simply use the wait()
and notify()
on a common lock
object.
From inside the main method, syncronize on the lock
object. Within the synchronized block start your another thread and invoke wait()
on the lock
object.
In the run method of your second thread , write a synchronized block on the lock
object and do your processing. Once it is done you can invoke the notify
on the same lock
object.
Main thread can then check if the required state has been set and then further actions can be decided (if you wish the main thread to complete its execution further or again wait and let second thread again do the processing) If you wish the second thread to again do (retry) the processing then like above you can invoke the notify()
on the lock
object and then can then invoke wait()
on the same lock
object.
This is the usual way of communication between two threads. But if its only single time process and you do not want it to happen multiple times then you can simply use the join()
method. Main thread can join on the second thread. Till the second thread will be processing its task the main thread will be waiting for the processing to complete. Once the second thread is executed completely (end of run ()
method) control will reach the maim thread.
I suggest you to have a look at these methods. consumer-producer
is a famous problem to understand these methods. You can also see these in action in an answer to another post.
https://stackoverflow.com/a/42049397/504133