1. 程式人生 > >python執行緒同步

python執行緒同步

import threading
import time

class mythread(threading.Thread):
    def __init__(self,threadID,name,counter):
        threading.Thread.__init__(self)
        self.threadID=threadID
        self.name=name
        self.counter=counter

    def run(self):
        print("開啟執行緒"+self.name)
        threadlock.acquire()#加鎖
        print_time(self.name,self.counter,3)
        threadlock.release()#解鎖

def print_time(threadname,delay,number):
    while number:
        time.sleep(delay)
        print("%s: %s"%(threadname,time.ctime(time.time())))
        number-=1

threadlock=threading.Lock()#建立鎖
threads=[]#建立空列表

#建立兩個執行緒
thread1=mythread(1,"thread_1",1)
thread2=mythread(2,"thread_2",2)

# 開啟新執行緒
thread1.start()
thread2.start()

# 新增執行緒到執行緒列表
threads.append(thread1)
threads.append(thread2)

# 等待所有執行緒完成
for t in threads:
    t.join()
print ("退出主執行緒")

#或者
# thread1.join()
# thread2.join()
# print ("退出主執行緒")