py:多线程使用

File : thread.py (直接右键另存为下载)
Type : python
Brief : python3多线程使用


import threading
import time

def func():
    print("Start func")
    time.sleep(1)
    print("Exit func")

class Pt(threading.Thread):
    lock = threading.Lock()

    def __init__(self, counter):
        threading.Thread.__init__(self)
        self.counter = counter;

    def run(self):
        """Thread function run"""
        print("Start " + self.name)
        self.lock.acquire()
        self.printTime(self.name, 1, self.counter)
        self.lock.release()
        print("Exit" + self.name)

    def printTime(self, name, delay, counter):
        while counter:
            counter -= 1
            time.sleep(delay)
            print("{}:{}".format(name, time.ctime(time.time())))

if __name__ == "__main__":
    t0 = threading.Thread(target=func)
    t1 = Pt(1)
    t2 = Pt(2)
    t0.start()
    t1.start()
    t2.start()
    t0.join()
    t1.join()
    t2.join()

转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 [ [email protected] ]