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

多线程 -- threading

时间:2018-08-28 17:02:05      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:war   __init__   targe   lis   --   pre   name   art   number   

  • 多线程的调用
    • 直接调用
      import threading
      import time
      
      #定义每个线程要运行的函数
      def my_func(num, **kwargs):
      
          print("%s running on number:%s" % (kwargs[‘name‘], num))
          time.sleep(3)
      
      if __name__ == ‘__main__‘:
          #生成一个线程实例
          t1 = threading.Thread(target=my_func, args=(1,), kwargs={‘name‘: ‘my_thread‘})
          #生成另一个线程实例
          t2 = threading.Thread(target=my_func, args=(2,), kwargs={‘name‘: ‘my_thread‘})
      
          #启动线程
          t1.start()
          #启动另一个线程
          t2.start()
      
          #获取线程名
          print(t1.getName())
          print(t2.getName())
      
    • 继承式调用
      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()
      

       

多线程 -- threading

标签:war   __init__   targe   lis   --   pre   name   art   number   

原文地址:https://www.cnblogs.com/dongmengze/p/9549232.html

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