线程创建的方法
方法一:
import time
import threading
def foo(n):
print('foo%s'%n)
time.sleep(1)
def bar(n):
print('bar%s'%n)
time.sleep(2)
t1 = threading.Thread(target=foo,args=(1,))
t2 = threading.Thread(target=bar,args=(2,))
方法二:
import threading
import time
class Mythread(threading.Thread):
def __init__(self,num):
threading.Thread.__init__(self)
self.num = num
def run(self):
print("running on number:%s"% self.num)
time.sleep(3)
if __name__ == '__main__':
t1 = Mythread(1)
t2 = Mythread(2)
t1.start()
t2.start()
start(),启动线程
join():join所完成的工作就是线程同步,即主线程任务结束之后,进入阻塞状态,一直等待其他的子线程执行结束之后,主线程在终止。
主线程会创建多个子线程,在python中,默认情况下(其实就是setDaemon(False)),主线程执行完自己的任务以后,就退出了,此时子线程会继续执行自己的任务,直到自己的任务结束。

785

被折叠的 条评论
为什么被折叠?



