python多線程併發測試

python多線程併發測試

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
import threading
import time
 
exitFlag = 0
 
class myThread (threading.Thread):   #繼承父類threading.Thread
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
    def run(self):                   #把要執行的代碼寫到run函數裏面 線程在創建後會直接運行run函數 
        print("Starting " + self.name)
        print_time(self.name, self.counter, 1)      # 這裏的最後一個參數1是指循環次數(1次)
        print("Exiting " + self.name)
 
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
 
# 創建新線程
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 1)
 
# 開啓線程
i = 0
for i in range(5):                                       #  這裏的range(5)是指線程數(5個)
	print("第{}次執行".format(i))
	myThread(1, "Thread-1", 1).start()
	# thread1.start()
	# thread2.start()
	
 
print("Exiting Main Thread")
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章