import threading
import time
exitFlag =0
class myThread(threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID= threadID #线程ID
self.name = name #线程名称
self.counter =counter #工作次数
def run(self):
print("开始线程" + self.name)
#获取线程锁,用于线程同步,在程序结束前,其他线程函数不会执行
threadLock.acquire()
print_time(self.name, self.counter, 5)
print("退出线程" + self.name)
#释放线程锁,开启下一个线程工作
threadLock.release()
#线程工作内容
def print_time(threadName, wait_sec, counter): #传入线程名称,延迟时间,工作次数
while counter:
if exitFlag:
threadName.exit()
time.sleep(wait_sec) #延迟时间
print("%s: %s" % (threadName, time.ctime(time.time())))
counter -=1
#创建线程锁,用于线程同步
threadLock =threading.Lock()
#创建线程列表,将线程放入线程列表中顺序执行
threads =[]
#创建新线程
thread1= myThread(1,"thread-1",1)
thread2= myThread(2,"thread-2",1)
#开启新线程
thread1.start()
thread2.start()
#将线程加入线程列表
threads.append(thread1)
threads.append(thread2)
#循环遍历线程函数,线程按顺序进行工作
for t in threads:
t.join()
print("退出主线程.......")