使用 threading 创建线程
用threading.Thread创建类,实例化,然后用start()调用,用join()等待线程结束
import threading
import time #引入
exitFlag = 0 #1时中断线程
class myThread (threading.Thread):
def __init__(self, threadID, name, delay):
threading.Thread.__init__(self)
self.threadID = threadID #定义线程id
self.name = name #线程名字
self.delay = delay #定义延迟时间
def run(self): #用start()启用线程会调用run()
print ("开始线程:" + self.name)
print_time(self.name, self.delay, 5) #调用print_time方法
print ("退出线程:" + self.name)
def print_time(threadName, delay, counter):
while counter:
if exitFlag:
threadName.exit() #貌似是退出线程
time.sleep(delay) #delay=1表示延时1秒
print ("%s: %s" % (threadName, time.ctime(time.time()))) #time.ctime(time.time())将当前时间转换为字符串并返回
counter -= 1
# 创建新线程
thread1 = myThread(1, "Thread-1", 1) #线程id,线程名,延时时间
thread2 = myThread(2, "Thread-2", 2)
# 开启新线程
thread1.start() #启动run方法
thread2.start()
thread1.join() #等待至该线程终止
thread2.join()
print ("退出主线程")
线程同步
#!/usr/bin/python3
import threading
import time
class myThread (threading.Thread):
def __init__(self, threadID, name, delay):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.delay = delay
def run(self):
print ("开启线程: " + self.name)
# 获取锁,用于线程同步
threadLock.acquire() #此时只执行此线程
print_time(self.name, self.delay, 3)
# 释放锁,开启下一个线程
threadLock.release() #此时执行下一个线程
def print_time(threadName, delay, counter):
while counter:
time.sleep(delay)
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", 2)
# 开启新线程
thread1.start()
thread2.start()
# 添加线程到线程列表
threads.append(thread1)
threads.append(thread2)
# 等待所有线程完成
for t in threads:
t.join()
#以上四句等同于##############
thread1.join()
thread2.join()
############################
print ("退出主线程")