发布于2019-12-14 16:41 阅读(987) 评论(0) 点赞(30) 收藏(0)
[url=][/url]
mport _thread as threadimport timedef loop1(in1): print("Start loop 1 at:",time.ctime()) print("我是参数",in1) time.sleep(4) print("End loop 1 at:",time.ctime())def loop2(in1,in2): print("Start loop 2 at:",time.ctime()) print("我是参数",in1,"和参数 ",in2) time.sleep(4) print("End loop 2 at:",time.ctime())import threadingdef main1(): print("Starting at:",time.ctime()) t1 = threading.Thread(target=loop1,args=('',)) t1.setName("THR_1")#给线程重命名 t1.start() t2 = threading.Thread(target=loop2,args=('','')) t2.setName("THR_2") t2.setDaemon(True) #主线程运行完了就完了,不用等线程2 t2.start() time.sleep(3)#三秒后两个子线程仍然在运行着,因为他们里面有一个四秒在停着 for thr inthreading.enumerate():#返回的是正在运行的子线程的列表 print("正在运行的子线程名为:{0}".format(thr.getName()))#读取了该线程的名字 print("正在运行的子线程数量为:{0}".format(threading.activeCount()))#打印出了线程的数量,包括主线程和两个子线程一共3个线程 t1.join()#等线程1运行完了再接着向下运行 print("ALL done at :",time.ctime())if __name__ == "__main__": main1()[url=][/url]
[url=]
[/url]
class MyThread(threading.Thread):#定义一个Thread的子类 def __init__(self,args):#重写__init__函数,其中参数为self和新引入的参数 super(MyThread,self).__init__()#固定格式,继承父类的__init__函数 self.args = args def run(self): time.sleep(1) print("The args for this class is {0}".format(self.args)) for i in range(5): t = MyThread(i) t.start() t.join()[url=]
[/url]
作者:听爸爸的话
链接:https://www.pythonheidong.com/blog/article/176581/1eedfc6b70fd3ac08920/
来源:python黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 python黑洞网 All Rights Reserved 版权所有,并保留所有权利。 京ICP备18063182号-1
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!