多线程同步引入锁

# _*_ coding: utf-8 _*_
__author__ = 'pythonwu'
__date__ = "2018/6/20 17:42"

import threading
import time

exitFlag = 10
class myThread(threading.Thread):
def __init__(self,threadID,name,counter):
threading.Thread.__init__(self) #重写父类的__init__方法
self.threadID = threadID
self.name = name
self.counter = counter

def run(self):
print("Starting " + self.name)
threadLock.acquire() #获得锁
print_time(self.name,self.counter,3) #执行程序
threadLock.release() #释放锁


def print_time(threadName,delay,counter):
while counter:
global exitFlag
time.sleep(2)
print("%s:%s" %(threadName,time.ctime(time.time())))
counter -= 1
exitFlag -= 1
print(exitFlag)

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("Exiting Main Thread")

 




posted @ 2018-06-20 18:04  五等码农  阅读(142)  评论(0编辑  收藏  举报