首页 > 代码库 > 基于类和基于函数的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多线程样例
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。