python多线程编程(1):使用Thread对象创建线程

tech2022-08-06  143

首先,读者需要带着对进程,主线程,子线程以及守护线程的理解或者疑惑进行理解学习多线程编程。

如果不理解也没关系,看几个程序就懂了

第一节:使用Thread对象创建线程

import threading, time, random def mission01(n): for i in range(5): time.sleep(random.choice(range(n))) thread_id = threading.get_ident() print('Thread:{},Time:{}'.format(thread_id,time.ctime())) def mission02(n): for i in range(5): time.sleep(random.choice(range(n))) thread_id = threading.get_ident()#获取当前线程标识符 print('Thread:{},i am fine,Time:{}'.format(thread_id,time.ctime())) def mission(): #为了查看效果,t1,t2两个线程去执行同一个函数,t3线程单独执行一个函数 t1 = threading.Thread(target=mission01, args=(5,))#创建线程1 t2 = threading.Thread(target=mission01, args=(5,))#创建线程2 t3 = threading.Thread(target=mission02, args=(5,)) # 创建线程3 t1.start(); t2.start();t3.start() if __name__ == '__main__': mission() ''' 通过创建Thread的对象,创建线程: Thread(target = None,name= None ,arg=(),kwargs={}) target:需要线程运行的函数 name:线程的名字 arg=(),kwargs={}:传递给target函数的参数元组和命名参数字典 ''' ''' 语法形式 t.start():启动线程 t.is_alive():判断线程是否活动 t.name:属性,线程名 t.id:返回线程标识符 threading.get_ident():返回当前线程的标识符(此处用来查看该线程在执行) threading.current_thread():返回当前线程 threading.active_couunt():返回活动的线程数目 threading.enumerate():返回活动线程的列表 '''

程序运行结果如下:

Thread:6280,Time:Wed Sep 2 21:18:40 2020 Thread:9776,Time:Wed Sep 2 21:18:42 2020 Thread:6280,Time:Wed Sep 2 21:18:42 2020 Thread:9776,Time:Wed Sep 2 21:18:43 2020Thread:13696,i am fine,Time:Wed Sep 2 21:18:43 2020 Thread:13696,i am fine,Time:Wed Sep 2 21:18:43 2020 Thread:13696,i am fine,Time:Wed Sep 2 21:18:44 2020 Thread:13696,i am fine,Time:Wed Sep 2 21:18:44 2020 Thread:9776,Time:Wed Sep 2 21:18:44 2020 Thread:6280,Time:Wed Sep 2 21:18:46 2020 Thread:13696,i am fine,Time:Wed Sep 2 21:18:47 2020 Thread:9776,Time:Wed Sep 2 21:18:48 2020 Thread:6280,Time:Wed Sep 2 21:18:49 2020 Thread:9776,Time:Wed Sep 2 21:18:49 2020 Thread:6280,Time:Wed Sep 2 21:18:52 2020 根据进程中输出的当前线程标识符可以发现,开启的三个线程都在同时执行。
最新回复(0)