#练习:创建一个线程 from threading import Thread import time def run(a = None, b = None) : print a, b time.sleep(1) t = Thread(target = run, name="wangjing",args = ("this is a", "thread")) #此时线程是新建状态 print t.getName() #获得线程对象名称 print t.isAlive() #判断线程是否还活着,在start后,在执行完毕前调用isAlive()才会返回True t.start() #启动线程 #print t.isAlive() t.join() #主线程等待子线程t执行结束 print "done!" #练习:用继承的方法创建线程 from threading import Thread import time class MyThread(Thread) : def __init__(self, a) : #调用父类的构造方法 super(MyThread, self).__init__() self.a = a def run(self) : time.sleep(self.a) print "sleep :", self.a t1 = MyThread(2) t2 = MyThread(4) #多线程的执行是没有顺序,本例主要是增加了较长的等待时间,才看起来有执行顺序 t1.start() t2.start() t1.join() t2.join() print "done!" #练习:线程 import threading import time class timer(threading.Thread): #The timer class is derived from the class threading.Thread def __init__(self, num, interval): threading.Thread.__init__(self) self.thread_num = num self.interval = interval self.thread_stop = False def run(self): #Overwrite run() method, put what you want the thread do here while not self.thread_stop: print 'Thread Object(%d), Time:%s ' %(self.thread_num, time.ctime()) time.sleep(self.interval) def stop(self): self.thread_stop = True def test(): thread1 = timer(1, 1) thread2 = timer(2, 2) thread1.start() #执行类里面的run方法 thread2.start() time.sleep(10) #这里是主线程等待10秒 thread1.stop() thread2.stop() #停止线程 #这里的停止是主线程调用的 if __name__ == '__main__': test() #练习:线程中再启动一个线程 import threading import time def context(tJoin): print 'in threadContext.' tJoin.start() # 将阻塞tContext直到threadJoin终止 tJoin.join() # tJoin终止后继续执行 print 'out threadContext.' def join1(): print 'in threadJoin.' time.sleep(1) print 'out threadJoin.' if __name__=="__main__": tJoin = threading.Thread(target = join1) #将线程对象作为参数传入另一个线程中 tContext = threading.Thread(target = context, args = (tJoin,)) tContext.start() #练习:将子线程设置为守护线程 import threading import time class MyThread(threading.Thread): def __init__(self, id): threading.Thread.__init__(self) def run(self): time.sleep(5) print "This is " + self.getName() if __name__ == "__main__": t1 = MyThread(999) #t1.setDaemon(True) # 将子线程设置为守护线程,设置为守护线程后,主线程退出子线程跟着退出,防止子线程挂起 t1.start() print "I am the father thread."