【2014-04-02】​python3下的多线程实例
2026/8/12 18:23:35 网站建设 项目流程

[历史归档]本文原发布于 cstriker1407.info 个人博客,内容为历史存档,仅供参考。
发布时间:2014-04-02| 标题:​python3下的多线程实例分类:编程 / python && jython |标签:多线程·python && jython


python3下的多线程实例

    • 最简单的多线程
      • 基于\_thread
      • 继承threading.Thread
      • 使用threading.Thread构造函数

本文的python版本:3.3.3

python的多线程代码网上到处都是,但是基于python3的不太好找,这里作者备份下最简单的3种实例。

python3的lib:

【 https://docs.python.org/3.3/library/threading.html#module-threading 】
【 https://docs.python.org/3.3/library/_thread.html#module-_thread 】

最简单的多线程

基于_thread

import_threadimporttimedefhello(index,count):whilecount>0:count=count-1;time.sleep(1);print("hello from %d, count = %d"%(index,count));if__name__=='__main__':_thread.start_new_thread(hello,(1,5));_thread.start_new_thread(hello,(2,8));

继承threading.Thread

importthreadingimporttimeclassHello(threading.Thread):def__init__(self,threadname,count):print("Hello Thread Init");threading.Thread.__init__(self,name=threadname)self.count=count;defrun(self):whileself.count>0:self.count=self.count-1;time.sleep(1);print("hello from %s, count = %d"%(self.name,self.count));if__name__=='__main__':thread1=Hello("A",5);thread2=Hello("B",8);thread1.start();thread2.start();

使用threading.Thread构造函数

importthreadingimporttimedefhello(index,count):whilecount>0:count=count-1;time.sleep(1);print("hello from %d, count = %d"%(index,count));if__name__=='__main__':thread1=threading.Thread(target=hello,args=(1,5));thread2=threading.Thread(target=hello,args=(2,8));thread1.start();thread2.start();

多线程同步及队列

暂时先略过。。

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询