python中threading是什么_举例详解Python中threading模块的几个常用方法

threading.Thread

Thread 是threading模块中最重要的类之一,可以使用它来创建线程。有两种方式来创建线程:一种是通过继承Thread类,重写它的run方法;另一种是创建一个threading.Thread对象,在它的初始化函数(__init__)中将可调用对象作为参数传入。下面分别举例说明。先来看看通过继承threading.Thread类来创建线程的例子:

#coding=gbk

import threading, time, random

count = 0

class Counter(threading.Thread):

def __init__(self, lock, threadName):

'''@summary: 初始化对象。

@param lock: 琐对象。

@param threadName: 线程名称。

'''

super(Counter, self).__init__(name = threadName)

#注意:一定要显式的调用父类的初始

化函数。

self.lock = lock

def run(self):

'''@summary: 重写父类run方法,在线程启动后执行该方法内的代码。

'''

global count

self.lock.acquire()

for i in xrange(10000):

count = count + 1

self.lock.release()

lock = threading.Lock()

for i in range(5):

Counter(lock, "thread-" + str(i)).start()

time.sleep(2)

#确保线程都执行完毕

print count

在代码中,我们创建了一个Counter类,它继承了threading.Thread。初始化函数接收两个参数,一个是琐对象,另一个是线程的名称。在Counter中,重写了从父类继承的run方法,run方法将一个全局变量逐一的增加10000。在接下来的代码中,创建了五个Counter对象,分别调用其start方法。最后打印结果。这里要说明一下run方法 和start方法: 它们都是从Thread继承而来的,run()方法将在线程开启后执行,可以把相关的逻辑写到run方法中(通常把run方法称为活动[Activity]。);start()方法用于启动线程。

再看看另外一种创建线程的方法:

import threading, time, random

count = 0

lock = threading.Lock()

def doAdd():

'''@summary: 将全局变量count 逐一的增加10000。

'''

global count, lock

lock.acquire()

for i in xrange(10000):

count = count + 1

lock.release()

for i in range(5):

threading.Thread(target = doAdd, args = (), name = 'thread-' + str(i)).start()

time.sleep(2)

#确保线程都执行完毕

print count

在这段代码中,我们定义了方法doAdd,它将全局变量count 逐一的增加10000。然后创建了5个Thread对象,把函数对象doAdd 作为参数传给它的初始化函数,再调用Thread对象的start方法,线程启动后将执行doAdd函数。这里有必要介绍一下threading.Thread类的初始化函数原型:

def __init__(self, group=None, target=None, name=None, args=(), kwargs={})

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值