Fixed the logic of stopping the threads