ITPub博客

首页 > 应用开发 > IT综合 > python线程调用方式

python线程调用方式

原创 IT综合 作者:5功啊 时间:2017-05-12 17:54:15 0 删除 编辑


1 直接调用


import threading
import time
 
def sayhi(num): #定义每个线程要运行的函数
 
    print("running on number:%s" %num)
 
    time.sleep(3)
 
if __name__ == '__main__':
 
    t1 = threading.Thread(target=sayhi,args=(1,)) #生成一个线程实例
    t2 = threading.Thread(target=sayhi,args=(2,)) #生成另一个线程实例
 
    t1.start() #启动线程
    t2.start() #启动另一个线程
 
    print(t1.getName()) #获取线程名
    print(t2.getName())



2 间接调用


import threading
import time
 
 
class MyThread(threading.Thread):
    def __init__(self,num):
        threading.Thread.__init__(self)
        self.num = num
 
    def run(self):#定义每个线程要运行的函数
 
        print("running on number:%s" %self.num)
 
        time.sleep(3)
 
if __name__ == '__main__':
 
    t1 = MyThread(1)
    t2 = MyThread(2)
    t1.start()
    t2.start()

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/26735168/viewspace-2139008/ ,如需转载,请注明出处,否则将追究法律责任。

上一篇: socket
下一篇: 没有了~
请登录后发表评论 登录
全部评论

注册时间:2016-07-07

  • 博文量
    38
  • 访问量
    32423