首页 > 代码库 > 基于类和基于函数的python多线程样例

基于类和基于函数的python多线程样例

不断的练,加深记忆吧。

#!/usr/bin/env python# -*- coding: utf-8 -*-import threading import timeexitFlag = 0def first_function():    print (threading.currentThread().getName() +            str( is Starting \n))    time.sleep(2)    print (threading.currentThread().getName() +            str( is Exiting \n))def second_function():    print (threading.currentThread().getName() +            str( is Starting \n))    time.sleep(2)    print (threading.currentThread().getName() +            str( is Exiting \n))def third_function():    print (threading.currentThread().getName() +            str( is Starting \n))    time.sleep(2)    print (threading.currentThread().getName() +            str( is Exiting \n))class myThread(threading.Thread):    def __init__(self, threadID, name, counter):        threading.Thread.__init__(self)        self.threadID = threadID        self.name = name        self.counter = counter    def run(self):        print("Starting " + self.name)        print_time(self.name, self.counter, 5)        print("Exiting " + self.name)def print_time(threadName, delay, counter):    while counter:        if exitFlag:            thread.exit()        time.sleep(delay)        print("%s: %s" % (threadName, time.ctime(time.time())))        counter -= 1        if __name__ == "__main__":    t1 = threading.Thread         (name=first_function, target=first_function)    t2 = threading.Thread         (name=second_function, target=second_function)    t3 = threading.Thread         (name=third_function, target=third_function)    t1.start()    t2.start()    t3.start()    t1.join()    t2.join()    t3.join()    thread1 = myThread(1, "Thread-1", 1)    thread2 = myThread(2, "Thread-2", 2)    thread1.start()    thread2.start()    thread1.join()    thread2.join()    print("Exiting Main Thread")        

技术分享

基于类和基于函数的python多线程样例