码迷,mamicode.com
首页 > 编程语言 > 详细

线程调用方式

时间:2017-05-12 22:08:43      阅读:122      评论:0      收藏: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()



线程调用方式

标签:线程

原文地址:http://bujuhandong.blog.51cto.com/1443515/1925146

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!