python有一个关于线程的threading模块,里面有一个Thread类。Thread类里有很多方法,包括run(),start(),getName(),setName(),join()等。run()可以通过继承重写,是线程运行时执行的内容。start()方法是启动一个线程,如定义继承Thread类的一个对象t,t.start()就启动这个线程,并自动执行run()方法。getName()是得到此线程的名字,setName是设置这个线程的名字,join()方法比较重要,如果代码中加入join(),是等待t这个线程执行完,才执行下一个线程。
当然Thread类里还有很多方法 setDaemon()方法,isAlive方法,isDaemon()方法等。
下面是第一个多线程程序。
import threading,random,time
class PrintThread(threading.Thread):
"""SubClass of threading.Thread"""
def __init__(self,threadName):
"""Initialize thread,set sleep time,print data"""
threading.Thread.__init__(self,name=threadName)
self.sleeptime=random.randrange(1,6)
print"Name: %s ; sleep: %d "%(self.getName(),self.sleeptime)
def run(self):
"""sleep for 1-5 seconds"""
print "%s going to sleep for %s seconds "\
%(self.getName(),self.sleeptime)
time.sleep(self.sleeptime)
print self.getName(),"done sleeping"
process_list=[]
for i in range(10):
threadName="thread"+str(i)
process_list.append(PrintThread(threadName))
for i in process_list:
i.start()
#i.join()
当没有加入i.join()时,执行结果如下,可以看到线程执行顺序是不定的。
当去掉i.join()前面的#时,执行结果如下,完全按顺序执行