首页 > 代码库 > python基础-线程创建方式

python基础-线程创建方式

python中提供了两种创建线程的方式

1.采用thread.start_new_thread(funciton,args..)

2.集成Thread类

 

第一种方式

import thread as timport time#Define a function for the threaddef 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 followstry:    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

实现步骤如下

  1. 申明一个Thread类的子类
  2. 覆盖_init_(slef,agrs)方法来增加额外的参数
  3. 实现线程逻辑

 但是有一个奇怪的问题是,run和start方式有很大的差别

import threading import timeexitFlag=0class 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.namedef 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 threadsthread1 = myThread(1,"Thread-1",1)thread2 = myThread(2,"Thread-2",3)#startthread1.start()thread2.start()#run和start不同,why?while thread2.isAlive():    if not thread1.isAlive():        exitFlag = 1        print "thread1 is over"    passprint "Exiting Main Thread"

 

线程同步

python基础-线程创建方式