theading模块的Thread类

属性:

    name   线程名

    ident   线程标识符

    daemon   布尔值,标示是否为守护线程

方法:

  __init__(target=None, name=None, *args=(), **kwargs={})

  start()   开始执行线程

  run()    定义线程功能的方法

  join(timeout=None)  阻塞线程,等待被唤醒,好于忙等待

Thread类的使用主要有三种方法:

1.创建Thread实例,传给其一个参数

2.创建Thread实例,传给其一个可调用的类实例

3.派生Thread子类,创建子类实例

下面介绍这三种用法:

1.创建Thread实例,传给其一个参数

 from threading import Thread
from time import ctime, sleep loops = [4, 2] def loop(nloop, nsec):
print('loops ', nloop, 'starting at:', ctime())
sleep(nsec)
print('loop', nloop, 'end at:', ctime()) def main():
print('starting at:', ctime())
threads = [] for i in range(len(loops)):
t = Thread(target=loop, args=(i,loops[i]))
threads.append(t)        ###保存类实例 for i in range(len(loops)):
threads[i].start()        ###同时启动类实例 for i in range(len(loops)):
threads[i].join()          ###保持主线程切出 print('all done at:', ctime()) if __name__ == '__main__':
main()

运行结果:

starting at: Mon Dec 19 23:29:58 2016
loops 0 starting at: Mon Dec 19 23:29:58 2016
loops 1 starting at: Mon Dec 19 23:29:58 2016
loop 1 end at: Mon Dec 19 23:30:00 2016
loop 0 end at: Mon Dec 19 23:30:02 2016
all done at: Mon Dec 19 23:30:02 2016

  方法1,传入函数创建类实例,不用人为设置锁,释放锁

方法二:传入可调用类创建类实例(用法感觉有点像装饰器)

 from threading import Thread
from time import ctime, sleep loops = [4, 2] class TFun():
def __init__(self, name, func, args):
self.name = name
self.func = func
self.args = args def __call__(self):
return self.func(*self.args) def loop(nloop, nsec):
print('loop ', nloop, 'at:', ctime())
sleep(nsec)
print('loop ', nloop, 'at:', ctime()) def main():
print('starting at:', ctime())
threads = [] for i in range(len(loops)):
t = Thread(target=TFun(loop.__name__, loop, (i,loops[i])))
threads.append(t) for i in range(len(loops)):
threads[i].start() for i in range(len(loops)):
threads[i].join() print('all done at:', ctime()) if __name__ == '__main__':
main()

运行结果:

starting at: Mon Dec 19 23:46:31 2016
loop 0 at: Mon Dec 19 23:46:31 2016
loop 1 at: Mon Dec 19 23:46:31 2016
loop 1 at: Mon Dec 19 23:46:33 2016
loop 0 at: Mon Dec 19 23:46:35 2016
all done at: Mon Dec 19 23:46:35 2016

方法三:

派生Thread子类,创建子类实例

 from threading import Thread
from time import ctime, sleep loops = [4, 2] class mythread(Thread):
def __init__(self, func, args, name=''):
Thread.__init__(self)
self.name = name
self.func = func
self.args = args
self.name = name def run(self): #注意不是__call__(self)
self.func(*self.args) def loop(nloop, nsec):
print('loop', nloop, 'at:', ctime())
sleep(nsec)
print('loop ', nloop, 'end at:', ctime()) def main():
print('starting at:', ctime())
threads = [] for i in range(len(loops)):
t = mythread(loop,(i,loops[i]))
threads.append(t) for i in range(len(loops)):
threads[i].start() for i in range(len(loops)):
threads[i].join() print('end at:', ctime()) if __name__ == '__main__':
main()

运行结果:

starting at: Tue Dec 20 00:06:00 2016
loop 0 at: Tue Dec 20 00:06:00 2016
loop 1 at: Tue Dec 20 00:06:00 2016
loop 1 end at: Tue Dec 20 00:06:02 2016
loop 0 end at: Tue Dec 20 00:06:04 2016
end at: Tue Dec 20 00:06:04 2016

  方法二和方法三可以测试多个函数,其中方法三更加直观。但是方法1更加简单

参考资料:Python核心编程.第四章.Wesley Chun著

【Python@Thread】threading模块的更多相关文章

  1. python中threading模块详解(一)

    python中threading模块详解(一) 来源 http://blog.chinaunix.net/uid-27571599-id-3484048.html threading提供了一个比thr ...

  2. Python使用Threading模块创建线程

    使用Threading模块创建线程,直接从threading.Thread继承,然后重写__init__方法和run方法: #!/usr/bin/python # -*- coding: UTF-8 ...

  3. 再看python多线程------threading模块

    现在把关于多线程的能想到的需要注意的点记录一下: 关于threading模块: 1.关于 传参问题 如果调用的子线程函数需要传参,要在参数后面加一个“,”否则会抛参数异常的错误. 如下: for i ...

  4. python中threading模块中最重要的Tread类

    Tread是threading模块中的重要类之一,可以使用它来创造线程.其具体使用方法是创建一个threading.Tread对象,在它的初始化函数中将需要调用的对象作为初始化参数传入. 具体代码如下 ...

  5. 学会使用Python的threading模块、掌握并发编程基础

    threading模块 Python中提供了threading模块来实现线程并发编程,官方文档如下: 官方文档 添加子线程 实例化Thread类 使用该方式新增子线程任务是比较常见的,也是推荐使用的. ...

  6. Python之Threading模块

    Thread 先引入一个例子: >>> from threading import Thread,currentThread,activeCount >>> > ...

  7. Python之threading模块的使用

    作用:同一个进程空间并发运行多个操作,专业术语简称为:[多线程] 1.任务函数不带参数多线程 #!/usr/bin/env python # -*- coding: utf-8 -*- import ...

  8. Python(多线程threading模块)

    day27 参考:http://www.cnblogs.com/yuanchenqi/articles/5733873.html CPU像一本书,你不阅读的时候,你室友马上阅读,你准备阅读的时候,你室 ...

  9. python中threading模块中的Join类

    join类是threading中用于堵塞当前主线程的类,其作用是阻止全部的线程继续运行,直到被调用的线程执行完毕或者超时.具体代码如下: import threading,time def doWai ...

  10. Python中threading模块的join函数

    Join的作用是阻塞进程直到线程执行完毕.通用的做法是我们启动一批线程,最后join这些线程结束,例如: for i in range(10): t = ThreadTest(i) thread_ar ...

随机推荐

  1. python绝技 — 使用PyGeoIP关联IP地址和物理位置

    准备工作 要关联IP与物理位置,我们需要有一个包含这样对应关系的数据库. 我们可以使用开源数据库GeoLiteCity,它能够较为准确地把IP地址与所在城市关联起来 下载地址:http://dev.m ...

  2. python绝技 — 侦听802.11 Probe请求

    代码 #!/usr/bin/python #--*--coding=utf-8--*-- from scapy.all import * interface = 'wlan1' probeReqs = ...

  3. 使用Stardict命令行版本sdcv

    sdcv命令的常用选项如下: -l:列出安装的词典 -u:指定查词所用的词典 在我的电脑上列出的词典有: Dictionary's name Word count Merrian Webster 10 ...

  4. 主成分分析(Principal components analysis)-最大方差解释

    原文:http://www.cnblogs.com/jerrylead/archive/2011/04/18/2020209.html 在这一篇之前的内容是<Factor Analysis> ...

  5. vue对比其他框架

    对比其他框架 React React 和 Vue 有许多相似之处,它们都有: 使用 Virtual DOM 提供了响应式(Reactive)和组件化(Composable)的视图组件. 将注意力集中保 ...

  6. [Q]系统环境改变导致“未注册”的解决方法

    据用户反映设置账户开机密码后显示未注册, 具体表现: 1. 重装试用版,重新获取注册申请码,发现注册申请码跟原来没有发生变化. 2. 重新使用原来的授权文件注册,但打开后显示未注册. 3. 发现“** ...

  7. Elasticsearch常用插件(三)

    elasticsearch-head 一个elasticsearch的集群管理工具,它是完全由html5编写的独立网页程序,你可以通过插件把它集成到es. 项目地址:https://github.co ...

  8. [ An Ac a Day ^_^ ] [kuangbin带你飞]专题十二 HDU 1176 免费馅饼

    题意: 中文题意不解释…… 思路: 先把x,T存到矩阵里 然后像数塔一样从最底层走一边就行了 dp[i][j]代表在时间为j时 第i个位置最多能吃到多少个馅饼 最后输出第0时刻的5位置的馅饼数量就好了 ...

  9. 编译搭建Lamp服务器

    Lamp 是目前倍受欢迎的一种网站服务器.其主要有linux+apache+mysql+php 组成.由于其组成成员都是开源免费的产品,所以被作为中小型网站服务器的选择.LZ之前在学校学linux的时 ...

  10. 我的JAvA第三天