#创建3个线程,每个线程包括2个子线程
import threading
import time
def process():
for i in range(2):
time.sleep(2)
print("线程的名称:{}".format(threading.currentThread().name))#threading.currentThread()获取当前线程
if __name__ == "__main__":
print("---主线程开始---")
threads=[threading.Thread(target=process) for i in range(3)]
for t in threads:
t.start()#等待线程启动
for t in threads:
t.join()
print("---主线程结束---")
#使用start_new_thread()产生新线程
import _thread
import time
#为线程创建一个函数,实现输出当前的时间
def print_time(threadname,delay):
count=0
print(time.ctime())
while count < 5:
count += 1
time.sleep(delay)
print(time.ctime())
try:
_thread.start_new_thread(print_time,("线程1",2))#第一个参数为函数名,第二个参数为函数的参数,以元组的形式传入
_thread.start_new_thread(print_time,('线程2',4))
except:
print("Error:无法启动线程")
while 1:
pass
© 版权声明
THE END
暂无评论内容