標籤:you ant als 構造 self write 返回 停止 阻塞
#練習:建立一個線程from threading import Threadimport timedef 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()才會返回Truet.start() #啟動線程#print t.isAlive()t.join() #主線程等待子線程t執行結束print "done!"#練習:用繼承的方法建立線程from threading import Threadimport timeclass 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\n‘ %(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 threadingimport timedef 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."
【Python】多線程-1