在Python中,可以使用threading模块来创建线程和销毁线程。
import threadingdef print_numbers(): for i in range(1, 6): print(i)t = threading.Thread(target=print_numbers)t.start()销毁线程:在Python中,线程通常是在函数运行结束后自动销毁的。但是可以使用join()方法来等待线程执行完成后再销毁线程。t.join()如果需要手动销毁线程,可以设置一个标志位来控制线程是否继续运行:
import threadingclass MyThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.is_running = True def run(self): while self.is_running: print("Thread is running...") def stop(self): self.is_running = Falset = MyThread()t.start()# 销毁线程t.stop()t.join() 



