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

655Z技术栈 Python编程 12小时前 4

在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()

提供PHP及ThinkPHP框架的定制开发、代码优化,PHP修改、ThinkPHP修改。

邮箱:yvsm@163.com 微信:yvsm316 QQ:316430983
关闭

用微信“扫一扫”