python中如何创建线程和销毁线程

avatar
作者
猴君
阅读量:0

在Python中,可以使用threading模块来创建线程和销毁线程。

  1. 创建线程:
import threading  def print_numbers():     for i in range(1, 6):         print(i)  t = threading.Thread(target=print_numbers) t.start() 
  1. 销毁线程: 在Python中,线程通常是在函数运行结束后自动销毁的。但是可以使用join()方法来等待线程执行完成后再销毁线程。
t.join() 

如果需要手动销毁线程,可以设置一个标志位来控制线程是否继续运行:

import threading  class 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 = False  t = MyThread() t.start()  # 销毁线程 t.stop() t.join()