Python中的线程threading对象
Python的线程开发使用标准库threading
进程靠线程执行代码,至少有一个主线程,其它线程是工作线程。
主线程是第一个启动的线程。
父线程:如果线程A中启动了一个线程B,A就是B的父线程。
子线程:B就是A的子线程。
Thread类
class threading.Thread(group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None) #线程
def __init__(self, group=None, target=None, name=None,args=(), kwargs=None, *, daemon=None)
pass
参数名 |
含义 |
target |
线程调用的对象,就是目标函数 |
name |
为线程起一个名字(线程的名字) |
args |
为目标函数传递实参,元组 |
kwargs |
为目标函数传递关键字参数,字典 |
线程并启动与退出
- 通过threading.Thread创建一个线程对象,target是目标函数,可以使用name为线程指定名称。
- 启动线程需要调用线程的start()方法才能启动
- 线程之所以执行函数,是因为线程中就是要执行代码的,而简单的封装就是函数,所以还是函数调用
- 线程执行完,线程就退出了
- Python没有提供线程退出的方法,线程在下面情况时退出
- 线程函数内语句执行完毕
- 线程函数中抛出未处理的异常
- Python的线程没有优先级、没有线程组的概念,也不能被销毁、停止、挂起,那也就没有恢复、中断了。
import threading
def worker():
print("hello word")
print("my name is xdd")
t = threading.Thread(target=worker,name="xdd")
t.start()
def add(x,y):
print("{} + {} = {}".format(x,y,x+y),threading.current_thread().ident)
tt = threading.Thread(target=add,name="xddadd",args=(3,),kwargs={
"y":15})
tt.start()
threading的属性和方法
名称 |
含义 |
threading.current_thread() |
返回当前线程对象 |
threading.current_thread().ident |
返回当前线程的id |
threading.main_thread() |
返回主线程(main线程)对象 |
threading.active_count() |
返回当前处于active状态的线程个数。(活着的,还未运行结束的线程个数) |
threading.enumerate() |
返回所有活着的线程列表,不包括已经终止的线程和未开始的线程 |
threading.getident() |
返回当前线程的ID,非0整数 |
- active_count,enumerate方法返回的值包含主线程。
import threading
def shothread():
print("- "*30)
print(threading.enumerate())
print(threading.active_count())
print(threading.get_ident())
print(threading.current_thread(),threading.current_thread().ident)
print(threading.main_thread())
shothread()
t = threading.Thread(target=shothread)
t.start()
Thread线程的实例对象的属性和方法
名称 |
含义 |
Thread.name |
线程的名字,一个标识符,线程的名称可以重名。getName(),setNa |