python多线程编程(五)

一、派生多线程。

开始时,Thread要完成一些基本初始化,然后调用其run方法,这会调用传递到构造函数的目标函数,要创建一个Thread子类,需要覆盖run()来完成所需工作。

import threading
import logging
import urllib2
logging.basicConfig(
    level = logging.DEBUG,
    format = '%(levelname)s (%(threadName)s) %(message)s',
	)

class MyThread(threading.Thread):
	def run(self):
		logging.debug('runing')
		logging.debug(threading.currentThread().getName())
		return
	def test(self):
		return 'nihao'
for i in range(6):
	t = MyThread()
	t.start()
	print t.test()
解释:以上代码比较简单,不解释

二、构造函数传递参数

由于传递到Thread构造函数的args和kwargs值保存在私有变量中,所以不能容易从子类访问这些值,要向一个定制的线程类型传递参数,需要重新定义构造函数,将这些值保存在子类可见的一个实例属性中。

import threading
import logging
import urllib2
logging.basicConfig(
    level = logging.DEBUG,
    format = '%(levelname)s (%(threadName)s) %(message)s',
	)

class MyThread(threading.Thread):

    def __init__(self,group=None,target=None,name=None,args=(),kwargs=None,verbose=None):
        threading.Thread.__init__(self,group=group,target=target,name=name,verbose=verbose)
        self.args = args
        self.kwargs = kwargs

    def run(self):
   
        logging.debug('running with %s and %s',
                       self.args,self.kwargs)
        return

for i in range(6):
    t = MyThread(args=(i,),kwargs={'a':'A','b':'B'})
    t.start()
结果:

DEBUG (Thread-1) running with (0,) and {'a': 'A', 'b': 'B'}
DEBUG (Thread-2) running with (1,) and {'a': 'A', 'b': 'B'}
DEBUG (Thread-3) running with (2,) and {'a': 'A', 'b': 'B'}
DEBUG (Thread-4) running with (3,) and {'a': 'A', 'b': 'B'}
DEBUG (Thread-5) running with (4,) and {'a': 'A', 'b': 'B'}
DEBUG (Thread-6) running with (5,) and {'a': 'A', 'b': 'B'}


三、定时器线程

有时出于某种原因需要派生Thread,Timer就是这样一个例子,Timer也包含在threading中。Timer在一个延迟之后开始工作,可以在这个延迟期间内任意时刻取消。

import threading
import logging
import time
logging.basicConfig(
    level = logging.DEBUG,
    format = '%(levelname)s (%(threadName)s) %(message)s',
	)

def delay():
    logging.debug('worker running')
    return
t1 = threading.Timer(3,delay)
t1.setName('t1')

t2 = threading.Timer(3,delay)
t2.setName('t2')

logging.debug('starting timers')
t1.start()
t2.start()
logging.debug('waiting befor canceling %s',t2.getName())
time.sleep(2)
logging.debug('canceling %s',t2.getName())
t2.cancel()
logging.debug('done')
结果:

DEBUG (MainThread) starting timers
DEBUG (MainThread) waiting befor canceling t2
DEBUG (MainThread) canceling t2
DEBUG (MainThread) done
DEBUG (t1) worker running
解释:

第二个定时器永远不会运行,第一个定时器会在其余的主程序完成之后运行。大家可以把延迟时间修改,查看程序的运行情况。

(未完待续)




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值