前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python多线程、阻塞线程、线程同步和守护线程实例详解

Python多线程、阻塞线程、线程同步和守护线程实例详解

作者头像
王大力测试进阶之路
发布2020-02-10 13:15:16
4.5K0
发布2020-02-10 13:15:16
举报
文章被收录于专栏:橙子探索测试橙子探索测试

一、多线程(主线程和子线程同时执行)

1、主线程是程序本身,看不到的,主线程和子线程没有依赖关系,同步执行的,若主线程先执行完,会等子线程执行完毕,程序结束

2、启动一个线程就是把一个函数传入并创建Thread实例,然后调用start()开始执行run()

3、threading.currentThread(): 返回当前的线程变量<Thread(Thread-1, started 8056)>、<_MainThread(MainThread, started 14400)>

threading.enumerate(): 返回一个包含正在运行的线程的list。正在运行指线程启动后、结束前,不包括启动前和终止后的线程;

threading.activeCount(): 返回正在运行的线程数量,与len(threading.enumerate())有相同的结果

run(): 用以表示线程活动的方法

start():启动线程活动

join(timeout): 等待至线程中止。这阻塞调用线程直至线程的join() 方法被调用中止-正常退出或者抛出未处理的异常-或者是可选的超时发生;

sAlive(): 返回线程是否活动的

getName(): 返回线程名;setName(): 设置线程名

4、多线程实例

代码语言:javascript
复制
#函数式多线程
import time,threading
def learnEnglish():
    print('%s 橙子在学习英语 %s'%(threading.currentThread(),time.ctime()))
def learnPython(name):
    print('%s %s在学习英语 %s'%(threading.currentThread(),name,time.ctime()))
def learnC(name,course):
    print('%s %s在学习%s %s'%(threading.currentThread(),name,course,time.ctime()))
start_time=time.time()
threads=[]# 创建线程数组
thread1=threading.Thread(target=learnEnglish)#创建线程
thread2=threading.Thread(target=learnPython,args=('橙汁',))
thread3=threading.Thread(target=learnC,args=('柠檬','C',))
thread4=threading.Thread(target=learnC,kwargs={"name":"王荔","course":"测试"})
threads.append(thread1)#将线程1添加到线程数组
threads.append(thread2)
threads.append(thread3)
threads.append(thread4)
for i in threads:
    i.start()#启动线程
run_times=(time.time()-start_time)
print('%s %s'%(threading.currentThread(),time.ctime()))
print('主线程和子线程运行时间共:%s'%run_times)
 
 
C:\Users\wangli\PycharmProjects\AutoMation\venv\Scripts\python.exe C:/Users/wangli/PycharmProjects/AutoMation/case/test.py
<Thread(Thread-1, started 5664)> 橙子在学习英语 Thu Mar 14 13:12:25 2019
<Thread(Thread-2, started 6964)> 橙汁在学习英语 Thu Mar 14 13:12:25 2019
<Thread(Thread-3, started 17908)> 柠檬在学习C Thu Mar 14 13:12:25 2019
<Thread(Thread-4, started 17816)> 王荔在学习测试 Thu Mar 14 13:12:25 2019
<_MainThread(MainThread, started 12276)> Thu Mar 14 13:12:25 2019
主线程和子线程运行时间共:0.0009965896606445312
 
Process finished with exit code 0
代码语言:javascript
复制
#多线程threading之封装
import threading,time
class MyThread(threading.Thread):#继承父类threading.Thread
    def __init__(self,name,people):
        '''重写threading.Thread初始化内容'''
        super(MyThread,self).__init__()
        self.threadName=name
        self.people=people
    def run(self):# 把要执行的代码写到run函数里面 线程在创建后会直接运行run函数
        print('开始线程%s %s'%(self.threadName,time.ctime()))
        print('结束线程%s %s'%(self.threadName,time.ctime()))
start_time=time.time()
print('开始主线程%s'%time.ctime())
thread1=MyThread('Thread-1','王荔')
thread2=MyThread('Thread-2','橙子')
thread1.start()
thread2.start()
print('退出主线程%s'%time.ctime())
run_times=(time.time()-start_time)
print('运行时间%s'%run_times)
 
 
C:\Users\wangli\PycharmProjects\AutoMation\venv\Scripts\python.exe C:/Users/wangli/PycharmProjects/AutoMation/case/test.py
开始主线程Thu Mar 14 13:16:10 2019
开始线程Thread-1 Thu Mar 14 13:16:10 2019
结束线程Thread-1 Thu Mar 14 13:16:10 2019
开始线程Thread-2 Thu Mar 14 13:16:10 2019
退出主线程Thu Mar 14 13:16:10 2019
运行时间0.0009996891021728516
结束线程Thread-2 Thu Mar 14 13:16:10 2019
 
Process finished with exit code 0
 
-----可以看到主线程和子线程是同时运行的,主线程运行完,子线程可能还在运行;子线程运行完,主线程可能还在运行

二、多线程之线程阻塞,子线程.join()(设置在start之后,等所有阻塞线程运行完,再运行主线程)

1、阻塞主线程必须在start()方法后执行,t1.join()等线程1运行完,t2.join()等线程2运行完,再运行主线程

2、如果想让主线程等待子线程结束后再运行,就需用到【子线程.join()】,此方法是在start后(与setDaemon相反)

3、join(timeout)此方法有个timeout参数,是线程超时时间设置

4、阻塞线程和非阻塞线程实例

代码语言:javascript
复制
#非阻塞线程,主线程休眠1s,子线程休眠3s
时间未统计到子线程,只统计到主线程的,说明主线程和子线程是同步执行的,且主线程执行完了,子线程还在执行
 
import threading,time
class MyThread(threading.Thread):#继承父类threading.Thread
    def __init__(self,name,people):
        '''重写threading.Thread初始化内容'''
        super(MyThread,self).__init__()
        self.threadName=name
        self.people=people
    def run(self):# 把要执行的代码写到run函数里面 线程在创建后会直接运行run函数
        print('开始线程%s %s'%(self.threadName,time.ctime()))
        time.sleep(3)
        print('结束线程%s %s'%(self.threadName,time.ctime()))
start_time=time.time()
print('开始主线程%s'%time.ctime())
thread1=MyThread('Thread-1','王荔')
thread2=MyThread('Thread-2','橙子')
thread1.start()
thread2.start()
#thread1.join()
#thread2.join()
print('退出主线程%s'%time.ctime())
time.sleep(1) 
run_times=(time.time()-start_time)
 
 
C:\Users\wangli\PycharmProjects\AutoMation\venv\Scripts\python.exe C:/Users/wangli/PycharmProjects/AutoMation/case/test.py
开始主线程Thu Mar 14 13:30:07 2019
开始线程Thread-1 Thu Mar 14 13:30:07 2019
开始线程Thread-2 Thu Mar 14 13:30:07 2019
退出主线程Thu Mar 14 13:30:07 2019
运行时间1.0023198127746582
结束线程Thread-1 Thu Mar 14 13:30:10 2019
结束线程Thread-2 Thu Mar 14 13:30:10 2019
 
Process finished with exit code 0
代码语言:javascript
复制
#阻塞线程1、阻塞线程2,主线程休眠1s,线程1和线程2休眠3s
主线程会等线程1和线程2执行完,才会继续执行主线程,统计时间为主线程1s+子线程3s=4s
import threading,time
class MyThread(threading.Thread):#继承父类threading.Thread
    def __init__(self,name,people):
        '''重写threading.Thread初始化内容'''
        super(MyThread,self).__init__()
        self.threadName=name
        self.people=people
    def run(self):# 把要执行的代码写到run函数里面 线程在创建后会直接运行run函数
        print('开始线程%s %s'%(self.threadName,time.ctime()))
        time.sleep(3)
        print('结束线程%s %s'%(self.threadName,time.ctime()))
start_time=time.time()
print('开始主线程%s'%time.ctime())
thread1=MyThread('Thread-1','王荔')
thread2=MyThread('Thread-2','橙子')
thread1.start()
thread2.start()
thread1.join()#阻塞线程1
thread2.join()#阻塞线程2
time.sleep(1)
print('退出主线程%s'%time.ctime())
run_times=(time.time()-start_time)
print('运行时间%s'%run_times)
 
C:\Users\wangli\PycharmProjects\AutoMation\venv\Scripts\python.exe C:/Users/wangli/PycharmProjects/AutoMation/case/test.py
开始主线程Thu Mar 14 13:35:29 2019
开始线程Thread-1 Thu Mar 14 13:35:29 2019
开始线程Thread-2 Thu Mar 14 13:35:29 2019
结束线程Thread-1 Thu Mar 14 13:35:32 2019
结束线程Thread-2 Thu Mar 14 13:35:32 2019
退出主线程Thu Mar 14 13:35:33 2019
运行时间4.004500389099121
 
Process finished with exit code 0
代码语言:javascript
复制
#阻塞线程实例
 
# coding=utf-8
import threading
import time
 
def chiHuoGuo(people):
    print("%s 吃火锅的小伙伴-羊肉:%s" % (time.ctime(),people))
    time.sleep(1)
    print("%s 吃火锅的小伙伴-鱼丸:%s" % (time.ctime(),people))
 
 
class myThread (threading.Thread):   # 继承父类threading.Thread
    def __init__(self, people, name):
        '''重写threading.Thread初始化内容'''
        threading.Thread.__init__(self)
        self.threadName = name
        self.people = people
 
    def run(self):   # 把要执行的代码写到run函数里面 线程在创建后会直接运行run函数
        '''重写run方法'''
        print("开始线程: " + self.threadName)
 
        chiHuoGuo(self.people)     # 执行任务
        print("qq交流群:226296743")
        print("结束线程: " + self.name)
 
print("yoyo请小伙伴开始吃火锅:!!!")
 
# 创建新线程
thread1 = myThread("xiaoming", "Thread-1")
thread2 = myThread("xiaowang", "Thread-2")
 
# 开启线程
thread1.start()
thread2.start()
 
# 阻塞主线程,等子线程结束
thread1.join()
thread2.join()
 
time.sleep(0.1)
print("退出主线程:吃火锅结束,结账走人")
 
 
C:\Users\wangli\PycharmProjects\AutoMation\venv\Scripts\python.exe C:/Users/wangli/PycharmProjects/AutoMation/case/test.py
yoyo请小伙伴开始吃火锅:!!!
开始线程: Thread-1
Thu Mar 14 13:41:10 2019 吃火锅的小伙伴-羊肉:xiaoming
开始线程: Thread-2
Thu Mar 14 13:41:10 2019 吃火锅的小伙伴-羊肉:xiaowang
Thu Mar 14 13:41:11 2019 吃火锅的小伙伴-鱼丸:xiaowang
qq交流群:226296743
结束线程: Thread-2
Thu Mar 14 13:41:11 2019 吃火锅的小伙伴-鱼丸:xiaoming
qq交流群:226296743
结束线程: Thread-1
退出主线程:吃火锅结束,结账走人
 
Process finished with exit code 0

三、守护线程(设置在start之前,设置子线程A为守护线程,主线程所在的进程内所有非守护线程统统运行完毕 ,无论子线程A有没有结束,程序都结束

1、主线程退出时,不等那些子线程完成,那就设置子线程为守护线程thread1.setDaemon(True)

2、设置一个线程为守护线程,就表示你在说这个线程不重要,在进程退出时,不用等待这个线程退出

3、程序在等待子线程结束,才退出,不需要设置线程守护,或者显示调用thread1.setDaemon(False)

4、主线程是非守护线程,只要还存在一个非守护线程,程序就不会退出。

5、守护线程必须在start()方法调用之前设置,如果不设置为守护线程,程序会被无限挂起

6、当有多个子线程时,守护线程就会等待所有的子线程运行完毕后,守护线程才会挂掉(这一点和主线程是一样的,都是等待所有的子线程运行完毕后才会挂掉)。

7、调用线程对象的方法setDaemon(true),则可以将其设置为守护线程。在python中建议使用的是thread.demon = true 使用这个方法可以检测数据合法性

8、setDaemon(True)此方法里面参数设置为True才会生效

9、对于主线程运行完毕,指的是主线程所在的进程内所有非守护线程统统都运行完毕,主线程才算运行完毕

10、守护线程实例

代码语言:javascript
复制
#设置线程1和线程2为守护线程
因为程序没有其他非守护线程,所以当主线程运行完,不等线程1和线程2,就直接结束
 
import threading,time
class MyThread(threading.Thread):#继承父类threading.Thread
    def __init__(self,name,people):
        '''重写threading.Thread初始化内容'''
        super(MyThread,self).__init__()
        self.threadName=name
        self.people=people
    def run(self):# 把要执行的代码写到run函数里面 线程在创建后会直接运行run函数
        time.sleep(3)
        print('开始线程%s %s'%(self.threadName,time.ctime()))
        print('结束线程%s %s'%(self.threadName,time.ctime()))
start_time=time.time()
print('开始主线程%s'%time.ctime())
thread1=MyThread('Thread-1','王荔')
thread2=MyThread('Thread-2','橙子')
thread1.setDaemon(True)#设置为守护线程
thread2.setDaemon(True)#设置为守护线程
thread1.start()
thread2.start()
print('退出主线程%s'%time.ctime())
run_times=(time.time()-start_time)
print('运行时间%s'%run_times)
 
C:\Users\wangli\PycharmProjects\AutoMation\venv\Scripts\python.exe C:/Users/wangli/PycharmProjects/AutoMation/case/test.py
开始主线程Thu Mar 14 13:59:09 2019
退出主线程Thu Mar 14 13:59:09 2019
运行时间0.0009975433349609375
 
Process finished with exit code 0
代码语言:javascript
复制
#将线程2设置为守护线程
当线程1和主线程运行完,程序立即结束;故会存在2种结果:
当线程1先结束,就不会执行线程2结束
当线程2先结束,就会出执行线程2结束
 
import threading,time
class MyThread(threading.Thread):#继承父类threading.Thread
    def __init__(self,name,people):
        '''重写threading.Thread初始化内容'''
        super(MyThread,self).__init__()
        self.threadName=name
        self.people=people
    def run(self):# 把要执行的代码写到run函数里面 线程在创建后会直接运行run函数
        print('开始线程%s %s'%(self.threadName,time.ctime()))
        time.sleep(3)
        print('结束线程%s %s'%(self.threadName,time.ctime()))
start_time=time.time()
print('开始主线程%s'%time.ctime())
thread1=MyThread('Thread-1','王荔')
thread2=MyThread('Thread-2','橙子')
#thread1.setDaemon(True)#设置为守护线程
thread2.setDaemon(True)#设置为守护线程
thread2.start()
thread1.start()
print('退出主线程%s'%time.ctime())
run_times=(time.time()-start_time)
print('运行时间%s'%run_times)
 
 
C:\Users\wangli\PycharmProjects\AutoMation\venv\Scripts\python.exe C:/Users/wangli/PycharmProjects/AutoMation/case/test.py
开始主线程Thu Mar 14 14:11:07 2019
开始线程Thread-2 Thu Mar 14 14:11:07 2019
开始线程Thread-1 Thu Mar 14 14:11:07 2019
退出主线程Thu Mar 14 14:11:07 2019
运行时间0.0009958744049072266
结束线程Thread-2 Thu Mar 14 14:11:10 2019
结束线程Thread-1 Thu Mar 14 14:11:10 2019
 
Process finished with exit code 0
 
 
C:\Users\wangli\PycharmProjects\AutoMation\venv\Scripts\python.exe C:/Users/wangli/PycharmProjects/AutoMation/case/test.py
开始主线程Thu Mar 14 14:13:03 2019
开始线程Thread-2 Thu Mar 14 14:13:03 2019
开始线程Thread-1 Thu Mar 14 14:13:03 2019
退出主线程Thu Mar 14 14:13:03 2019
运行时间0.0009908676147460938
结束线程Thread-1 Thu Mar 14 14:13:06 2019
 
Process finished with exit code 0
代码语言:javascript
复制
#守护线程实例
 
# coding=utf-8
import threading
import time
 
def chiHuoGuo(people):
    print("%s 吃火锅的小伙伴-羊肉:%s" % (time.ctime(),people))
    time.sleep(1)
    print("%s 吃火锅的小伙伴-鱼丸:%s" % (time.ctime(),people))
 
 
class myThread (threading.Thread):   # 继承父类threading.Thread
    def __init__(self, people, name):
        '''重写threading.Thread初始化内容'''
        threading.Thread.__init__(self)
        self.threadName = name
        self.people = people
 
    def run(self):   # 把要执行的代码写到run函数里面 线程在创建后会直接运行run函数
        '''重写run方法'''
        print("开始线程: " + self.threadName)
 
        chiHuoGuo(self.people)     # 执行任务
        print("qq交流群:226296743")
        print("结束线程: " + self.name)
 
print("yoyo请小伙伴开始吃火锅:!!!")
 
# 创建新线程
thread1 = myThread("xiaoming", "Thread-1")
thread2 = myThread("xiaowang", "Thread-2")
 
# 守护线程setDaemon(True)
thread1.setDaemon(True)       # 必须在start之前
thread2.setDaemon(True)
 
# 开启线程
thread1.start()
thread2.start()
 
time.sleep(0.1)
print("退出主线程:吃火锅结束,结账走人")
 
C:\Users\wangli\PycharmProjects\AutoMation\venv\Scripts\python.exe C:/Users/wangli/PycharmProjects/AutoMation/case/test.py
yoyo请小伙伴开始吃火锅:!!!
开始线程: Thread-1
Thu Mar 14 14:22:20 2019 吃火锅的小伙伴-羊肉:xiaoming
开始线程: Thread-2
Thu Mar 14 14:22:20 2019 吃火锅的小伙伴-羊肉:xiaowang
退出主线程:吃火锅结束,结账走人
 
Process finished with exit code 0
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-12-30,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 橙子探索测试 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档