python进阶(3)
线程
定义
单线程测试,默认情况下,程序启动只有一个线程,这个线程就是主线程,线程是CPU调度的基本单位
统计线程的个数
import threading
print("hello")
print("#####统计当前线程运行的个数#######")
print(threading.active_count())
注意点:
- 在没有添加进程的情况下,我们依旧可以找到一个线程,这个线程是主线程
创建多线程
def __init__(self, group=None, target=None, name=None,
args=(), kwargs=None, *, daemon=None):
"""This constructor should always be called with keyword arguments. Arguments are:
*group* should be None; reserved for future extension when a ThreadGroup
class is implemented.
*target* is the callable object to be invoked by the run()
method. Defaults to None, meaning nothing is called.
*name* is the thread name. By default, a unique name is constructed of
the form "Thread-N" where N is a small decimal number.
*args* is the argument tuple for the target invocation. Defaults to ().
*kwargs* is a dictionary of keyword arguments for the target
invocation. Defaults to {}.
If a subclass overrides the constructor, it must make sure to invoke
the base class constructor (Thread.__init__()) before doing anything
else to the thread.
"""
线程的注意点
-
线程的调度是无序的,因为是CPU调度的
-
守护主线程,主线程退出,子线程销毁
import threading import time def calm_down(): for i in range(10): time.sleep(1) print("第",i,"冷静一下") def smoke(): for j in range(10): time.sleep(1) print("第",j,"只烟") if __name__ == '__main__': print("当前的线程个数:",threading.active_count()) # 创建多线程 thread_somke=threading.Thread(target=smoke) print("当前的线程个数:",threading.active_count()) thread_calm=threading.Thread(target=calm_down) #守护主线程 thread_somke.setDaemon(True) thread_calm.setDaemon(True) # 调用多线程 thread_somke.start() thread_calm.start() # time.sleep(2) print("当前的线程个数:",threading.active_count()) print("主线程已经结束")
-
守护子线程,只有所有子线程结束之后,主线程才结束
import threading import time def calm_down(): for i in range(10): time.sleep(1) print("第",i,"冷静一下") def smoke(): for j in range(10): time.sleep(1) print("第",j,"只烟") if __name__ == '__main__': print("当前的线程个数:",threading.active_count()) # 创建多线程 thread_somke=threading.Thread(target=smoke) print("当前的线程个数:",threading.active_count()) thread_calm=threading.Thread(target=calm_down) # 调用多线程 # thread_somke.run() thread_somke.start() thread_calm.start() # time.sleep(2) thread_calm.join() thread_somke.join() print("当前的线程个数:",threading.active_count()) print("主线程已经结束")