这篇文章主要介绍了python 多线程threading程序详情,Thread类表示在单独的控制线程中运行的活动
线程简介
Thread类表示在单独的控制线程中运行的活动。指定活动有两种方法:将可调用对象传递给构造函数,或重写子类中的run()方法。子类中不应重写任何其他方法(构造函数除外)。换句话说,只重写这个类的_init__;()和run()方法
一旦线程活动开始,该线程会被认为是 '存活的' 。当它的run() 方法终结了(不管是正常的还是抛出未被处理的异常),就不是'存活的'。
class threading.Thread(group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None)
- group:官方的解释是,为了日后扩展ThreadGroup类实现而保留。(唉,我也不太清楚的)
- target:是要于多线程的函数
- name:是线程的名字
- args :函数的参数,类型是元组()
- kwargs:函数的参数,类型是字典{}
为了便于理解,先举一个小例子,为了方便理解,先简单了解一下该类的一个方法(函数在类中被称为方法): - start():开始线程活动
import threading
import time
# 打印函数a
def printa(a):
count = 0
while count < 5:
time.sleep(2)
print("线程:%s。打印:%s。时间:%s。" % (threading.current_thread().name, a, time.ctime()))
count += 1
# 打印函数b
def printb(b):
count = 0
while count < 5:
time.sleep(4)
print("线程:%s。打印:%s。时间:%s。" % (threading.current_thread().name, b, time.ctime()))
count += 1
# threading.Thread(target=,args=(),name='')
t1 = threading.Thread(target=printa, args=(10,), name='线程1')
t2 = threading.Thread(target=printb, args=(20,), name='线程2')
t1.start()
t2.start()
t1.join()
t2.join()
print("退出主线程")
import threading
import time
# 打印函数a
def printa(a):
count = 0
while count < 5:
time.sleep(2)
print("线程:%s。打印:%s。时间:%s。" % (threading.current_thread().name, a, time.ctime()))
count += 1
# threading.Thread(target=,args=(),name='')
threadList = []
for i in range(3):
t = threading.Thread(target=printa, args=(i,))
threadList.append(t)
for t in threadList:
t.start()
for t in threadList:
t.join()
print("退出主线程")
关于线程Threading的方法(获取线程的某种属性)。
- active_count():它会获得,执行这个方法时,还存活的Thread()的对象数量。
- enumerate():返回当前所有存活的Thread对象的列表。
- current_thread():返回当前调用者 控制Thread()线程的对象。如果调用者控制的线程对象不是由threading创建,则会返回一个功能受限的虚拟线程对象。
- get_ident():返回当前线程的“线程标识符”。它是一个非零整数。
- get_native_id():返回内核分配给当前线程的原生集成线程ID。这是一个非负整数。
- main_thread():返回主线程(thread)对象,一般是python解释器开始时创建的线程。
发表评论
取消回复