Python多线程

本文介绍了线程与进程的基本概念,强调线程是程序执行的最小单位,进程则是资源分配的最小单位。在同一进程中,线程共享内存空间和资源。文章还探讨了如何在Python中创建多线程,并提到了线程的调度和切换,以及线程的特性,如使用time.time()计算运行时间,通过t1.join()进行线程等待,利用threading.active_count()获取活动线程数,以及threading.current_thread()获取当前线程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

线程与进程

1.线程是程序执行的最小单位,而进程是操作系统分配资源的最小单位;

2.一个进程由一个或多个线程组成,线程是一个进程中代码的不同执行路线

3.进程之间相互独立,但同一进程下的各个线程之间兵享程序的内存空间〔包括代码段,数据集,堆等)及一些进程级的资源(如打开文件和信号等)。某进程内的线程在其他进程不可见;

4.调度和切换:线程上下文切换比进程上下文切换要快得多

创建多线程

类的方法创建多线程

import threading

class MyThread(threading.Thread):
    #构造函数,用于传参
    def __init__(self,n):
        super(MyThread, self).__init__()
        self.n=n
    #启动线程的方法必须是run
    def run(self):
        print("以类的方式创建多线程",self.n)

t1=MyThread(11)
t2=MyThread(22)
t1.start()
t2.start()

多线程特性

计算线程运行时间    time.time()

import time
def run(x):
    print(f"线程{x}")#格式化字符串
    time.sleep(2)
    
start_time=time.time()
run(1)
run(2)
#1970年到现在一共走了多少秒
print(time.time())
#程序一共走了多长时间
print(f"一共运行了{time.time()-start_time}")

线程的等待   t1.join()

t1=threading.Thread(target=run,args=(1,))
t2=threading.Thread(target=run,args=(2,))
t1.start()
t1.join()#等待一个线程
t2.start()

查看活动线程

threading.active_count()

查看当前线程

threading.current_thread()

例题:

 

import threading
import time

class MyThread(threading.Thread):
    def __init__(self):
        super(MyThread, self).__init__()
    def run(self):
        while True:
            time.sleep(1)  # 每秒循环
            print(time.strftime('%Y-%m-%d %X'))  # 输出当前年月日 时分秒
class MyThread2(threading.Thread):
    def __init__(self):
        super(MyThread2, self).__init__()
    def run(self):
        while True:
            time.sleep(2)  # 每两秒循环
            for i in range(4):
                print("张三")  # 输出张三

t1=MyThread()
t2=MyThread2()
#线程启动
t1.start()
t2.start()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值