Add finalize method to ensure ending thread.