python线程

本文介绍了线程的基础概念及两种实现方式:通过函数和类。详细展示了使用Python的_thread和threading模块来创建和管理线程的具体方法,并解释了线程的五种基本状态。

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

实现线程有两种

A、函数  (需要导入模块_thread) B、类(需要导入模块threading)

线程5种状态:创建,就绪,,运行,阻塞,死亡

一、函数实现线程

import _thread
import time
def print_time(threadName,delay):
    count=0
    while count<5:
        time.sleep(delay)
        count+=1
        print("%s:%s"%(threadName,time.ctime(time.time()) ))
print_time('test',2)

线程加一个name实例:

def test(threadName):
    for i in range(20):
        print(threadName,i)
_thread.start_new_thread(test,("th1",))
_thread.start_new_thread(test,("th2",))
input("")

input("")为了让方法一直执行

二、类实现线程

import threading
import time
class ThreadTest(threading.Thread):
    def __init__(self,name):
        threading.Thread.__init__(self)
        self.name=name
    def run(self):
        for i in range(10):
            print(self.name,i)
            time.sleep(1)
t=ThreadTest("th1")
t.start()
t2=ThreadTest("th2")
t2.start()

线程的常用方法:threading.currentThread() 返回当前线程变量
threading.enumerate():返回一个包含正在运行的线程的list。正在运行指线程启动后,结束前,不包括启动前和终止后的线程
threading.activeCount():返回正在运行的线程数量,与len(threading.enumerate())有相同的结果
run():用以线程活动的方法
join([time]):加入线程
isAlive():返回线程是否活动的
getName():返回线程名

setName():设置线程名

调用start():方法是就绪

run():方法运行

 sleep():休息一段时间自己就运行了, 挂起,唤起





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值