Use wait and notify properly

- Use wait and notify instead of while loop
- Add a max retry count to avoid infinite loop