# -*- codeing: utf-8 —*—
import time
import threading
# 使用 threading 模块创建线程
class MyThread(threading.Thread):
def __init__(self, name, delay):
threading.Thread.__init__(self)
self.name = name
self.delay = delay
def run(self):
print("开始线程: " + self.name)
print_time(self.name, self.delay, 5)
print("退出线程: " + self.name)
pass
def print_time(thread_name, delay, counter):
"""
打印时间
:param thread_name: 线程名称
:param delay: 延迟时长
:param counter: 计数器
:return:
"""
while counter:
time.sleep(delay)
print("%s: %s" % (thread_name, time.strftime("%Y-%m-%d %H:%M:%S")))
counter -= 1
pass
# 创建新线程
thread1 = MyThread("Thread-1", 1)
thread2 = MyThread("Thread-2", 2)
# 开启新线程
thread1.start() # 启动线程活动。
thread2.start()
thread1.join() # 等待至线程中止。
thread2.join()
print("退出主线程")