实现线程有两种
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():休息一段时间自己就运行了, 挂起,唤起