Python中可以使用threading模块来实现多线程。使用步骤如下:
导入线程模块
## python www.itzhimei.com 代码 import threading
创建线程类,继承threading.Thread
## python www.itzhimei.com 代码 class MyThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): # 线程执行代码 pass
创建线程对象调用start()方法启动线程
## python www.itzhimei.com 代码 thread1 = MyThread() thread1.start() thread2 = MyThread() thread2.start()
线程示例:
## python www.itzhimei.com 代码 import threading def print_nums(): for i in range(10): print(i) t1 = threading.Thread(target=print_nums) t2 = threading.Thread(target=print_nums) t1.start() t2.start() # 输出交替打印nums
多线程可以用来执行耗时任务或异步任务,提高程序效率。需要注意线程同步和共享资源问题。