创建多线程常用的三种方法:

  • 创建Thread的实例,传给它一个函数
  • 创建Thread的实例,传给它一个可调用的类实例(不推荐)
  • 派生Thread的子类,并创建子类的实例(推荐)

创建Thread的实例,传给它一个函数

 #!/usr/bin/env python
# coding:utf-8 import threading
from time import ctime, sleep loops = [4, 2] def loop(n, sec):
print 'start loop', n, ' at: ', ctime()
sleep(sec)
print 'loop', n, ' done at: ', ctime() def main():
print 'starting at: ', ctime()
threads = []
nloops = range(len(loops)) for i in nloops:
t = threading.Thread(target=loop, args=(i, loops[i]))
threads.append(t) for i in nloops: # start threads
threads[i].start() for i in nloops: # wait for all threads to finish
threads[i].join() print 'all DONE at: ', ctime() if __name__ == '__main__':
main()

执行结果:

liuqian@ubuntu:~$ python test_threading1.py
starting at:  Wed Jul 20 13:20:06 2016
start loop 0  at:  Wed Jul 20 13:20:06 2016
start loop 1  at:  Wed Jul 20 13:20:06 2016
loop 1  done at:  Wed Jul 20 13:20:08 2016
loop 0  done at:  Wed Jul 20 13:20:10 2016
all DONE at:  Wed Jul 20 13:20:10 2016

【说明】

join([timeout])方法将等待线程结束,或者在提供了超时时间的情况下达到超时时间。对于join()方法而言,其实它根本不需要调用。一旦线程启动,它就会一直执行,直到给定的函数完成后退出。如果主线程还有其他事情要去做,而不是等待这些线程完成(例如其他处理或者等待新的客户端请求),就可以不调用join()。join()只在你需要等待线程完成的时候才是有用的。

创建Thread的实例,传给它一个可调用的类实例

 #!/usr/bin/env python
# coding:utf-8 import threading
from time import ctime, sleep loops = [4,2] class ThreadFunc(object): def __init__(self, func, args, name=''):
self.name = name
self.func = func
self.args = args def __call__(self):
self.func(*self.args) def loop(n, sec):
print 'start loop', n, ' at: ', ctime()
sleep(sec)
print 'loop', n, ' done at: ', ctime() def main():
print 'starting at: ', ctime()
threads = []
nloops = range(len(loops)) for i in nloops:
t = threading.Thread(target=ThreadFunc(loop, (i, loops[i]), loop.__name__))
threads.append(t) for i in nloops: # start threads
threads[i].start() for i in nloops: # wait for all threads to finish
threads[i].join() print 'all DONE at: ', ctime() if __name__ == '__main__':
main()

输出与第一个案例一样。

【说明】当创建新线程时,Thread类的代码将调用ThreadFunc对象,此时会调用__cal__()这个特殊方法。

派生Thread的子类,并创建子类的实例(推荐)

 #!/usr/bin/env python
# coding:utf-8 import threading
from time import ctime, sleep loops = [4,2] class MyThread(threading.Thread): def __init__(self, func, args, name=''):
threading.Thread.__init__(self)
self.name = name
self.func = func
self.args = args def run(self): # 必须要写
self.func(*self.args) def loop(n, sec):
print 'start loop', n, ' at: ', ctime()
sleep(sec)
print 'loop', n, ' done at: ', ctime() def main():
print 'starting at: ', ctime()
threads = []
nloops = range(len(loops)) for i in nloops:
t = MyThread(loop, (i, loops[i]), loop.__name__)
threads.append(t) for i in nloops: # start threads
threads[i].start() for i in nloops: # wait for all threads to finish
threads[i].join() print 'all DONE at: ', ctime() if __name__ == '__main__':
main()

Python 之 threading的更多相关文章

  1. python中threading的用法

    摘自:http://blog.chinaunix.net/uid-27571599-id-3484048.html 以及:http://blog.chinaunix.net/uid-11131943- ...

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

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

  3. python多线程threading.Lock锁用法实例

    本文实例讲述了python多线程threading.Lock锁的用法实例,分享给大家供大家参考.具体分析如下: python的锁可以独立提取出来 mutex = threading.Lock() #锁 ...

  4. Python 线程(threading) 进程(multiprocessing)

    *:first-child { margin-top: 0 !important; } body>*:last-child { margin-bottom: 0 !important; } /* ...

  5. Python 线程(threading)

    Python 的thread模块是比较底层的模块,Python的threading模块是对thread做了一些包装,可以更加方便的 被使用; 1. 使用threading 模块 # 示例一: 单线程执 ...

  6. Python之threading多线程,多进程

    1.threading模块是Python里面常用的线程模块,多线程处理任务对于提升效率非常重要,先说一下线程和进程的各种区别,如图 概括起来就是 IO密集型(不用CPU) 多线程计算密集型(用CPU) ...

  7. Python的threading和multiprocessing

    Python的threading 基础用法, 通过 threading.Thread() 创建线程, 然后 start() 和 join() import time import threading ...

  8. python使用threading获取线程函数返回值的实现方法

    python使用threading获取线程函数返回值的实现方法 这篇文章主要介绍了python使用threading获取线程函数返回值的实现方法,需要的朋友可以参考下 threading用于提供线程相 ...

  9. python:threading多线程模块-创建线程

    创建线程的两种方法: 1,直接调用threading.Thread来构造thread对象,Thread的参数如下: class threading.Thread(group=None, target= ...

随机推荐

  1. Notes of 大数据智能

    资料 刘知远 等. 大数据智能:互联网时代的机器学习和自然语言处理技术. 北京:电子工业出版社. 2016. 1 深度学习--机器大脑的结构 深度学习(Deep Learning)的两个方面: 神经网 ...

  2. C# 之泛型详解

    转自牛人博客:http://www.blogjava.net/Jack2007/archive/2008/05/05/198566.html 鄙人才疏学浅,经常遇到泛型,一知半解,用的时候也是模糊不清 ...

  3. 两个不同的list随机组合到一个List中。

    今天组长给了一个绑定任务,业务需要把一男一女随机的老师绑定到考场. 测试例子入下: package com.test; import java.util.ArrayList; import java. ...

  4. 遥感影像滤波处理软件 — timesat3.2

    最近因为要做遥感影像的滤波处理,经过女神推荐,决定用Timesat,可是该软件3.1版本只适合xp系统以及2011的matlab,后来在官网上找到了最新的3.2版本.支持64位操作系统以及2014的m ...

  5. Weblogic新增域(可以配置新端口)

    操作系统 :Linux version 2.6.32-504.el6.x86_64 Weblogic Server :11g 一.Weblogic新增域(可以配置新端口) 以weblogic用户登录 ...

  6. angular2 笔记

    动态添加一个component: import { ViewContarinerRef, Component, ComponentFactoryResolver, ViewChild } from ' ...

  7. pyspider 简单应用之快速问医生药品抓取(一)

    网址:http://yp.120ask.com/search/-0-0--0-0-0-0.html from pyspider.libs.base_handler import * class Han ...

  8. 《C与指针》第十四章练习

    本章问题 1.预处理器定义了5个符号,给出了进行编译的文件名.文件行的当前行号,当前日期和时间以及编译器是否为ANSI C编译器.为每个符号举出一种可能的用途. answer:在打印错误信息时,文件名 ...

  9. texturepacker打包图片,场景切换时背景图有黑边

    在使用TexturePacker打包图片之后,背景图在场景切换(有切换动画)时,明显能看到有黑边,在百度之后解决了. 知乎上边有网友贴出了两种解决方法,我抄过来如下: 第一种: 修改 ccConfig ...

  10. WebAPI学习点滴(二)

    刚开始学习WebApi就遇到了问题,在同一个API控制器中,如果两个方法的签名相同,比如 [HttpGet] public string GetString() { return "Hell ...