Refactored thread handling