本篇内容介绍了“Python线程的常用属性以及直接继承子类threading.Thread的过程”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
一、线程常用属性
1.threading.currentThread:返回当前线程变量
2.threading.enumerate:返回一个包含正在运行的线程的list,正在运行的线程指的是线程启动后,结束前的状态
3.threading.activeCount:返回正在运行的线程数量,效果跟len(threading.enumer)一样
4.thr.setName:给线程设置名字
5.thr.getName:得到线程的名字。
举例:
mport _thread as thread
import time
def 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 threading
def 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 in threading.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()
二、直接继承子类threading.Thread
1.直接继承Thread;重写run函数
2.例子:
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()
“Python线程的常用属性以及直接继承子类threading.Thread的过程”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。