Python 多线程其他属性以及继承Thread类详解

yipeiwu_com4年前Python基础

一、线程常用属性

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()

三、源码

d24_3_other_multi_thread_attribute.py

https://github.com/ruigege66/Python_learning/blob/master/d24_3_other_multi_thread_attribute.py

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

使用 Python 获取 Linux 系统信息的代码

哪个Python版本? 当我提及Python,所指的就是CPython 2(准确的是2.7).我会显式提醒那些相同的代码在CPython 3 (3.3)上是不工作的,以及提供一份...

python编程测试电脑开启最大线程数实例代码

python编程测试电脑开启最大线程数实例代码

本文实例代码主要实现python编程测试电脑开启最大线程数,具体实现代码如下。 #!/usr/bin/env python #coding=gbk import thr...

Django-Rest-Framework 权限管理源码浅析(小结)

Django-Rest-Framework 权限管理源码浅析(小结)

在django的views中不论是用类方式还是用装饰器方式来使用rest框架,django_rest_frame实现权限管理都需要两个东西的配合: authentication_clas...

python实现梯度下降算法

python实现梯度下降算法

梯度下降(Gradient Descent)算法是机器学习中使用非常广泛的优化算法。当前流行的机器学习库或者深度学习库都会包括梯度下降算法的不同变种实现。 本文主要以线性回归算法损失函数...

Python计算已经过去多少个周末的方法

本文实例讲述了Python计算已经过去多少个周末的方法。分享给大家供大家参考。具体如下: def weekends_between(d1,d2): days_between =...