前言:
学习多线程表面上可以理解为提高效率,充分利用资源。
python有两个模块可以学习,一个是比较简单的_thread模块,另一个是提供比较多集成方法的threading模块(推荐)。
_thread使用方法:
_thread.start_new_thread(func,args[,kargs]) : 第一个参数是线程函数,第二个是传递给线程函数的参数,第三个是可选参数
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())))
try:
_thread.start_new_thread(print_time,("Thread-1",2,) )
_thread.start_new_thread(print_time,("Thread-2",4,) )
except:
print("Error:无法启动线程")
while 1:
pass
threading使用方法:
包含_thread的所有方法
threading.currentThread():返回当前线程变量
threading.enumerate():返回包含正在运行的线程的list
threading.activeCount():返回正在运行的线程的数量
对象方法:
run():用来表示线程活动的方法
start():启动线程
join(time):可添加超时设置
isAlive():返回线程是否活动的
getName():返回线程名字
setName():设置线程名字
import threading
import time
exitFlag = 0
class myThread(threading.Thread):
def __init__(self,threadID,name,counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print("开始线程:"+self.name)
print_time(self.name,self.counter,5)
print("退出线程:"+self.name)
def print_time(threadName,delay,counter):
while counter:
print(threading.current_thread)
print(threading.enumerate)
print(threading.activeCount)
if exitFlag:
threadName.exit()
time.sleep(delay)
print("%s:%s" % (threadName,time.ctime(time.time())))
counter -= 1
thread1 = myThread(1,"Thread-1",1)
thread2 = myThread(2,"Thread-2",2)
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print(thread1.isAlive())
print(threading.current_thread)
print(threading.enumerate)
print("退出主线程")
线程同步:
创建锁对象:
threadLock = threading.Lock()
获取锁:
threadLock.acquire()
释放锁:
threadLock.release()