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()
        #===========================================================================
        
    

      

  • 相关阅读:
    EAX、ECX、EDX、EBX寄存器的作用
    MFC VS2005 添加Override 和 Message
    ActiveX添加测试工程, 出现的问题[非选择性参数][找不到成员]
    两种应该掌握的排序方法--------2.quick Sort
    关于I/O的那点事
    整理一下 编码、解码库
    VC一些经验系列: 《分享泄漏检测工具:内存、DC、GDI、Handle... 》
    golang安装卸载 linux+windows+raspberryPI 平台
    (转)如何正确使用C++多重继承
    单播、多播(也称组播)、广播
  • 原文地址:https://www.cnblogs.com/2012harry/p/2845264.html
Copyright © 2011-2022 走看看