improved timing of thread handling by using wait() instead of sleep