Python 多线程 入门学习 (二) 持续更新中

上篇文章中 简单的理解了Python多线程。

从上面例子中发现线程的创建是颇为麻烦的,每创建一个线程都需要创建一个game,music等,如果创建的线程多时候这样极其不方便。下面对通过例子进行继续改进:

# -*- coding: UTF-8 -*-
from time import ctime,sleep
import threading

class DuoThread(threading.Thread):
    def __init__(self,func,args,name=''):
         threading.Thread.__init__(self)
         self.name=name
         self.func=func      
         self.args=args
    def run(self):
        apply(self.func,self.args)
        

def play(file,time):
    for i in range(2):
        print"Start playing: %s!%s"%(file,ctime())
        sleep(time)

list={"name.mp3":3,"hello.mp4":5}
threads=[]
files=range(len(list)) 
for k,v in list.items():
     t=DuoThread(play,(k,v),play.__name__)
     threads.append(t)
         
    
if __name__ == '__main__': 
    print "Thread start %s" %ctime()
    for i in files:
       print "%s Threading  %s" %(i,ctime())
       threads[i].start()
    for i in files:
       threads[i].join()

   
    print "all over %s" %ctime()

    
    
apply(func [, args [, kwargs ]]) 函数用于当函数参数已经存在于一个元组或字典中时,间接地调用函数。args是一个包含将要提供给函数的按位置传递的参数的元组。如果省略了args,任何参数都不会被传递,kwargs是一个包含关键字参数的字典。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值