#!/usr/bin/python
# -*- coding: UTF-8 -*-
#主要通过threading模块实现多线程
import threading
import time
exitFlag = 0
def print_time(threadName, delay, counter):
while counter:
# if exitFlag:
# (threading.Thread).exit()
time.sleep(delay)
print ("%s: %s" % (threadName, time.ctime(time.time())))
counter -= 1
class myThread (threading.Thread): #继承父类threading.Thread
def __init__(self, threadID, name, delay): #myThread中参数
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.delay = delay
def run(self): #把要执行的代码写到run函数里面 线程在创建后会直接运行run函数
print ("Starting " + self.name)
print_time(self.name, self.delay, 5)
print ("Exiting " + self.name)
# 创建新线程
thread1 = myThread(1, "Thread-1", 2)
thread2 = myThread(2, "Thread-2", 3)
# 开启线程
thread1.start()
thread2.start()
print ("Exiting Main Thread")
#如果线程数比较多的话,通过for循环启动多线程
totalThread = 5
threadpool=[]
for i in range(totalThread):
new_thread = myThread(i,"thread-"+str(i),2)
threadpool.append(new_thread)
for th in threadpool:
th.start()
for th in threadpool:#等待所有线程完成
th.join() #通过join ,可以让线程在这里等着,阻塞在这里,等线程跑完了, 在继续跑下面的代码.
print ("Exiting Main Thread")
网友评论