标签:style blog io color ar for sp div on
python中提供了两种创建线程的方式
1.采用thread.start_new_thread(funciton,args..)
2.集成Thread类
第一种方式
import thread as t import time #Define a function for the thread def print_time(threadName,delay): count=0; while count<5: time.sleep(delay) count+=1 print "%s(%s): %s " %(threadName,count,time.ctime(time.time())) #Create two threads as follows try: t.start_new_thread(print_time,("thread-1",2)) t.start_new_thread(print_time,("thread-2",3)) except: print "Error:unable to start thread" while 1: pass
2.继承Thread
实现步骤如下
但是有一个奇怪的问题是,run和start方式有很大的差别
import threading import time exitFlag=0 class myThread(threading.Thread): #implement thead def __init__(self,threadID,name,delay): threading.Thread.__init__(self) self.threadID=threadID self.name=name self.delay=delay def run(self): print "Starting "+ self.name print_time(self.name,self.delay,5) print "Exiting "+ self.name def print_time(threadName,delay,counter): while counter: if exitFlag: thread.exit() time.sleep(delay) print ("%s(%s): %s"%(threadName,counter,time.ctime(time.time()))) counter -=1; #Create new threads thread1 = myThread(1,"Thread-1",1) thread2 = myThread(2,"Thread-2",3) #start thread1.start() thread2.start()#run和start不同,why? while thread2.isAlive(): if not thread1.isAlive(): exitFlag = 1 print "thread1 is over" pass print "Exiting Main Thread"
线程同步
标签:style blog io color ar for sp div on
原文地址:http://www.cnblogs.com/alwaysthinking/p/4067918.html