threading方法:
image.png
获取当前线程对象: import threading import time
def function(i): print("function called by thread %i" % i) print(threading.currentThread().getName()) threads=[] for i in range(5): t=threading.Thread(target=function,args=(i,)) threads.append(t) t.start() t.join()
class MyThread(Thread): def init(self, name='PHP'): super().init() # 注意: super().init() 一定要写,而且要写在最前面,否则会报错。 self.name=name
def run(self): # 类似于方法1中的自定义线程函数,方法的覆写
for i in range(2):
print('hello %s' % self.name)
time.sleep(1)
if name == 'main': thread_03 = MyThread() # 创建线程03,不指定参数 thread_04 = MyThread('Java',) # 创建线程024,指定参数
thread_03.start()
thread_04.start()