• python多线程1线程创建


    线程的创建的例子,小结了一下线程创建的方法。个人觉得还是第三种用的爽,虽然以前写Linux下的线程,都是用的第二种多一点。

    ps:第一种很少用,python推荐用threading模块代替thread模块了。api也有变化和废弃。

    #coding:gbk
    '''
    Created on 2013-1-4
    
    @author: Jimmy
    '''
    
    import thread
    import threading
    import time
    
    
    class Mthread(threading.Thread):     #我的timer类继承自threading.Thread类   
        def __init__(self, para, ThreadName):    
            #在我重写__init__方法的时候要记得调用基类的__init__方法   
            threading.Thread.__init__(self)
            self.setName(ThreadName)
            print para,ThreadName
               
        def run(self):  #重写run()方法,把自己的线程函数的代码放到这里
            print "ThreadName:" + self.getName()
            self.func()
            pass
        def func(self):
            print "我们需要执行的线程函数,要满足线程函数的特点,可重入的函数"
        
    def test(a,b):
        print a,b
        time.sleep(5)
        print "time 5s"
        
    def test1(a,b):
        print a,b
        print "time 5s"
    
    if __name__ == "__main__":
        '''
        1、线程第一种 thread.start_new_thread(test, (1,2))  返回的线程号
                   原型start_new_thread(function, args[, kwargs]),但是不能显式的传参数
        '''
        #threadnum = thread.start_new_thread(test1, (1,2))
        '''
        2、线程第二种  th = threading.Thread(target=worker,args=(a,b)),返回的是线程对象
                     无论是否超时,join返回的都是None;下面是设置超时的一种方式,当超时后,线程结束运行,主函数继续执行。可以显式的传参数  
        '''
        #===========================================================================
        # th = threading.Thread(target = test, args = (1,2))
        # #下面是设置超时
        # th.setDaemon(True)
        # th.start()
        # th.join(2)
        # print "run 2s"
        #===========================================================================
        
        '''
        3、Mthread("ClassThread","jimmy")
        2和3创建方式本质是一样的:一种是使用threading模块,一种继承threading模块重新自己的线程类
        '''
        #===========================================================================
        # th = Mthread("ClassThread","jimmy")
        # th.start()
        #===========================================================================
        
    

      

  • 相关阅读:
    GitHub(二)之修改项目语言类型
    GitHub(一)之图片上传问题
    Git入门操作(一)
    树莓派小白教程六部曲
    关于Ajax请求的JS封装函数
    JavaScript运动_封装模板(支持链式运动、完美运动)
    NAT-地址转换技术的配置
    JAVA连接Sql-Server教程
    Kibana对数据的可视化
    浏览器渲染机制
  • 原文地址:https://www.cnblogs.com/2012harry/p/2845264.html
Copyright © 2020-2023  润新知