zoukankan      html  css  js  c++  java
  • python多线程

    python多线程有两种用法,一种是在函数中使用,一种是放在类中使用

    1、在函数中使用

    定义空的线程列表

    threads=[]

    创建线程

    t=threading.Thread(target=函数名,args=(函数参数,必须为元组类型))#若函数中没有参数,则args参数可省略不写

    将线程加到线程列表中

    threads.append(t)

    运行线程

    for t in threads:

      t.setDaemon(True)  #这个也是守护线程,与join方法不同的是,它守护的是主线程,而join方法守护的是子线程。可以理解为这两个方法的作用正好相反。

      t.start()

    for t in threads:

      t.join()    #守护线程,join()可以传参,如join(5),表示超过5s就会直接跳出线程,直接执行下面的代码

    2、创建线程类

    class MyThread(threading.Thread):

      def __init__(self,func,args):

        super(MyThread,self).__init__() #super 方法是python中类子类继承父类用到的方法,可以保证父类中的方法只被调用一次。另一种写法是直接用父类名调用,效果是一样的。threading.Thread.__init__(self)

        self.func=func

        self.args=args

      def run(self):

        self.func(*self.args)

    def print_boy(num):

      for i in range(num):

        print "I am boy %s,Now the time is:%s"%(i,time.strftime("%H:%M:%S"))

        time.sleep(4)

    创建空的线程列表

    threads=[]

    创建线程

    t=MyThread(print_boy,(3,)) #注意这里传参的时候,必须是元组的形式

    加入线程列表

    threads.append(t)

    运行线程
    for t in threads:

      t.start()

    for t in threads:

      t.join()

  • 相关阅读:
    跳出iframe
    leetcode 225. Implement Stack using Queues
    leetcode 206. Reverse Linked List
    leetcode 205. Isomorphic Strings
    leetcode 203. Remove Linked List Elements
    leetcode 198. House Robber
    leetcode 190. Reverse Bits
    leetcode leetcode 783. Minimum Distance Between BST Nodes
    leetcode 202. Happy Number
    leetcode 389. Find the Difference
  • 原文地址:https://www.cnblogs.com/zhoufankui/p/6187673.html
Copyright © 2011-2022 走看看