refactoring the code, fix the bug of not exiting thread when close.