python 多线程编程

      使用threading模块的Thread类来创建线程,介绍常用的三种方法:

1.创建一个Thread类的实例,传入一个函数

#coding=utf-8
import threading, time
loops=[4,2]
def func(index, sec):
      print "func starts:%d"%(index)+"  %s\n"%(time.ctime())
      time.sleep(sec)
      print "func ends:%d"%(index)+"  %s\n"%(time.ctime())
def main():
     threads =[]
     nloop = range(nlen(loops))
     for i in nloop:
          tt = threading.Thread(target=func, args=(i, loops[i]))
          print "the name of the threadind:%s\n"%(tt.getName())
          threads.append(tt)
  
     for i in nloop:
          threads[i].start()

     for i in nloop:
           threads[i].join()  #允许主线程等待所有的线程运行完之后在执行后面的逻辑
     print "all done:%s\n"%(time.ctime())

if __name__ == "__main__":
     main()
2.创建一个Thread类实例,传入以个可调用的类对象

#coding=utf-8
import time, threading
loops=[4,2]

class MyThread(object):
      def __init__(self, func, args,name=""):
          self.args = args
          self.func = func
          self.name = name

      def __call__(self, *args, **kwargs):
          self.func(*self.args)

def loop(nloop, nsec):
    print "loop starts:%d"%(nloop) + "  %s\n"%(time.ctime())
    time.sleep(nsec)
    print "loop ends:%d"%(nloop) + "  %s\n"%(time.ctime())

def main():
    threads =[]
    for i in range(len(loops)):
        tt = threading.Thread(target=MyThread(loop, (i,loops[i]),loop.__name__))  #仅修改了这里
        print "线程名字:",tt.getName()
        threads.append(tt)
    for i in range(len(loops)):
        threads[i].start()

    for item in threads:
        item.join()

    print "all done:%s\n"%(time.ctime())

if __name__ == "__main__":
    main()
3.子类化Thread类,创建一个子类的实例

#coding=utf-8
import threading,time
loops=[4,2]
class MyThread(threading.Thread):
     def __init__(self,index, sec):
         threading.Thread.__init__(self)
         self.index = index
         self.sec = sec

     def run(self):
         print "loop starts:%d"%(self.index) + "  %s\n"%(time.ctime())
         time.sleep(self.sec)
         print "loop ends:%d"%(self.sec) + "  %s\n"%(time.ctime())

def main():
    nloop = range(len(loops))
    threads = []
    for i in nloop:
        tt = MyThread(i,loops[i])
        print "线程名字:",tt.getName()
        threads.append(tt)
    for i in range(len(loops)):
        threads[i].start()

    for item in threads:
        item.join()

    print "all done:%s\n"%(time.ctime())


if __name__ == "__main__":
    main()


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值