Day13 线程与进程
1.threading模块
–单线程执行
enumerate() 函数:
用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标。可以用enumerate()来查看线程的进行程度。
–当出现调用thread时,不会创建线程,线程会跑到test1里去执行
def main():
t1=threading.Thread(target=test1)
print(threading.enumerate())
[<_MainThread(MainThread, started 4445822400)>]
–当调用start后,才算创建了线程以及运行线程
t1=threading.Thread(target=test1)
print(threading.enumerate())
t1.start()
print(threading.enumerate())
[<_MainThread(MainThread, started 4445822400)>, <Thread(Thread-1, started 123145407184896)>]
2.继承thread类创建线程
定义一个子类,通过继承threading.Thread,可以完成线程的封装。
import threading
import time
class MyThread(threading.Thread):
def run(self):
for i in range(3):
time.sleep(1)
msg="I'm "+self.name+' &#