How to wait for all threads to finish