多线程:在某些程序段中并行执行代码,提高工作效率
实现:线程交叉执行,使用交替串行实现并行
import threading # 多线程模块
# class定义线程
class A(threading.Thread): # 线程A
def __init__(self): # 初始化线程的方法
threading.Thread.__init__(self)
def run(self): # 该线程应该执行的操作
for i in range(0,10):
print("线程A")
class B(threading.Thread): # 线程B
def __init__(self): # 初始化线程的方法
threading.Thread.__init__(self)
def run(self): # 该线程应该执行的操作
for i in range(0,10):
print("线程B")
t1 = A() # 实例化线程A
t1.start() # 启动t1指向的线程
t2 = B() # 实例化线程B
t2.start() # 启动t1指向的线程