zoukankan      html  css  js  c++  java
  • 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()
        #===========================================================================
        
    

      

  • 相关阅读:
    php写的几种常见算法
    无状态登陆:JWT
    boostrap中日期控件使用
    boostrap中文件上传使用组件fileinput
    ubuntu环境下homestead安装运行nsq
    Ubuntu 下修改mysqlroot密码
    从git到lnmp代码发布
    maven的xml中报错:org.apache.maven.archiver.MavenArchiver.getManifest(org.apache.maven.project.MavenProject, org.apache.maven.archiver.MavenArchiveConfiguration)
    给mysql查询添加序号列
    maven jar包下载不下来
  • 原文地址:https://www.cnblogs.com/2012harry/p/2845264.html
Copyright © 2011-2022 走看看