开启线程
1、如何开启线程?类似开启进程一样
方式一:
from threading import Thread import random import time def piao(name): print("%s piaoing" % name) time.sleep(random.randrange(1,5)) print("%s piao end" % name) if __name__ =="__main__": t=Thread(target=piao,args=("ya",)) t.start() print("The main thread is end.")
方式二:
import time import random from threading import Thread class MyThread(Thread): def __init__(self,name): super().__init__() self.name=name def run(self): print("%s piaoing" % self.name) time.sleep(random.randrange(1,5)) print("%s pia end" % self.name) if __name__=="__main__": p=MyThread("Test MyThread") p.start() print("The main thread is done.")