多線程的優勢:
可以同時運行多個任務
但是當多個線程同時訪問共享數據時,可能導致數據不同步,甚至錯誤!
so,不使用線程鎖, 可能導致錯誤
購買車票--線程鎖
[root@~]# cat test.py
#-*- coding:utf-8 -*- import threading import time tickets = range(1,10) def buy_ticket(station): while True: mylock.acquire() #加線程鎖 if len(tickets) == 0: mylock.release() #釋放線程鎖, 不要帶鎖結束線程 break; ticket = tickets[-1] time.sleep(1) print "%s買到票No.%d" %(station, ticket) del tickets[-1] mylock.release() #釋放線程鎖 time.sleep(1) class MyThread(threading.Thread): def __init__(self, station): threading.Thread.__init__(self) self.station = station #線程啓動後,會執行self.run()方法 def run(self): buy_ticket(self.station) # 創建一個線程鎖 mylock = threading.Lock() # 創建新線程t1 t1 = MyThread("廣州") t2 = MyThread("深圳") t1.start() #啓動線程 t2.start() print "線程啓動完畢" print 'end.'
結果:
[root@~]# python test.py