手机版
你好,游客 登录 注册 搜索
背景:
阅读新闻

Python之多线程编程学习笔记

[日期:2013-02-03] 来源:Linux社区  作者:sssogs [字体:大 中 小]

2.创建threading模块中的Thread类实现多线程

这个模块是高层模块,使用起来相对于thread模块更方便一些。

先实例化一个Thread对象,传入work_one和work_two函数,在调用start方法,启动线程。最后用join方法,等待线程退出。

import threading
from time import sleep
def work_one():
    print 'John starts to work!\n'
    sleep(4)    #模拟工作过程
    print 'John done his work!\n'
 
   
def work_two():
    print 'Billy starts to work!\n'
    sleep(6)    #模拟工作过程
    print 'Billy done his work!\n'             
   
def main():
    print '***** main *****\n'
    thread1=threading.Thread(target=work_one) #创建一个Thread实例
    thread2=threading.Thread(target=work_two)
    thread1.start()                          #start函数,启动线程                       
    thread2.start()
    thread1.join()                            #join函数,用于等待线程结束
    thread2.join()
    print '***** all work done! *****\n'
if __name__ == '__main__':
main()

3.继承Thread类,创建子类实例

编写一个MyThread类,继承,并覆盖run方法。然后再调用start和join方法。

import threading
from time import sleep
class Mythread(threading.Thread):
    def __init__(self,time,name):
        threading.Thread.__init__(self)
        self.time=time
        self.name=name
    def run(self):
        sleep(self.time)    #模拟工作过程
       
def main():
    print '***** main *****'
    thread1=Mythread(4,'John') #创建一个Thread实例
    thread2=Mythread(6,'Billy')
    print thread1.name,'starts to work!'
    thread1.start()                          #start函数,启动线程
    print thread2.name,'starts to work!'
    thread2.start()
    thread1.join()                            #join函数,用于等待线程结束
    print thread1.name,'done his work!'
    thread2.join()
    print thread2.name,'done his work!'
    print '***** all work done! *****\n'
if __name__ == '__main__':
main()

效果图如下:

linux
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款