标签:print out splay pen tar blocks cat closed view
一、线程的使用
需导入模块: from threading import Thread
二、基本使用
1 def fun1(arg1, v): 2 print(arg1) 3 4 print(‘before‘) 5 t1 = Thread(target=fun1, args=(‘aaa‘,11,)) 6 t1.start() 7 print(‘此线程名称:‘, t1.getName()) 8 9 t2 = Thread(target=fun1, args=(‘bbb‘,22,)) 10 t2.start() 11 print(‘此线程名称:‘, t2.getName()) 12 13 print(‘after‘)
三、常用方法
1 def fun2(): 2 for i in range(100): 3 print(i) 4 time.sleep(1) 5 6 print(‘start‘) 7 t1 = Thread(target=fun2) 8 print(‘是否守护线程:‘, t1.isDaemon()) #默认为False,自动执行 9 #设置为守护线程,不自动执行,主程序执行完则子线程不执行, 10 #主程序如果没执行完,则子线程随着主程序执行,直至主程序结束,子线程也跟着结束 11 t1.setDaemon(True) 12 t1.start() 13 print(‘after1‘) 14 print(‘after2‘) 15 print(‘after3‘) 16 time.sleep(10)
1 def fun1(): 2 for i in range(10): 3 print(i) 4 time.sleep(1) 5 6 print(‘before‘) 7 t1 = Thread(target=fun1) 8 t1.start() 9 # t1.join() #主程序执行到join()这里后挺住开始执行子线程,子线程执行结束后主程序继续执行 10 t1.join(5) #最多等5秒,子线程最多执行5秒后主进程继续向下执行,主程序执行结束后,子线程继续执行 11 12 print(‘after‘)
四、自定义线程类
1 class MyThread(Thread): 2 def run(self): 3 time.sleep(3) 4 print(‘我是线程‘) 5 Thread.run(self) #如果不加此句,则不会执行自定义线程中的函数 6 7 def Bar(): 8 print(‘bar‘) 9 10 t1 = MyThread(target=Bar) 11 t1.start() 12 print(‘over‘)
标签:print out splay pen tar blocks cat closed view
原文地址:http://www.cnblogs.com/crucial/p/6107100.html