Python多线程编程简单介绍

yipeiwu_com5年前Python基础

创建线程

格式如下

复制代码 代码如下:

threading.Thread(group=None, target=None, name=None, args=(), kwargs={})

这个构造器必须用关键字传参调用
- group 线程组
- target 执行方法
- name 线程名字
- args target执行的元组参数
- kwargs target执行的字典参数

Thread对象函数

函数 描述
start() 开始线程的执行
run() 定义线程的功能的函数(一般会被子类重写)
join(timeout=None) 程序挂起,直到线程结束;如果给了 timeout,则最多阻塞 timeout 秒
getName() 返回线程的名字
setName(name) 设置线程的名字
isAlive() 布尔标志,表示这个线程是否还在运行中
isDaemon() 返回线程的 daemon 标志
setDaemon(daemonic) 把线程的 daemon 标志设为 daemonic(一定要在调用 start()函数前调用)

常用示例

格式

复制代码 代码如下:

import threading

def run(*arg, **karg):
    pass
thread = threading.Thread(target = run, name = "default", args = (), kwargs = {})
thread.start()


实例
复制代码 代码如下:

#!/usr/bin/python
#coding=utf-8

import threading
from time import ctime,sleep

def sing(*arg):
    print "sing start: ", arg
    sleep(1)
    print "sing stop"


def dance(*arg):
    print "dance start: ", arg
    sleep(1)
    print "dance stop"

threads = []

#创建线程对象
t1 = threading.Thread(target = sing, name = 'singThread', args = ('raise me up',))
threads.append(t1)

t2 = threading.Thread(target = dance, name = 'danceThread', args = ('Rup',))
threads.append(t2)

#开始线程
t1.start()
t2.start()

#等待线程结束
for t in threads:
    t.join()

print "game over"


输出
复制代码 代码如下:

sing start:  ('raise me up',)
dance start:  ('Rup',)
sing stop
dance stop
game over

相关文章

Python 绘图和可视化详细介绍

Python之绘图和可视化 1. 启用matplotlib 最常用的Pylab模式的IPython(IPython --pylab) 2. matplotlib的图像都位于Figure对...

用Python中的__slots__缓存资源以节省内存开销的方法

用Python中的__slots__缓存资源以节省内存开销的方法

我们曾经提到,Oyster.com的Python web服务器怎样利用一个巨大的Python dicts(hash table),缓存大量的静态资源。我们最近在Image类中,用仅仅一行...

python Pillow图像处理方法汇总

这篇文章主要介绍了python Pillow图像处理方法汇总,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 Pillow中文文档:ht...

python静态方法实例

本文实例讲述了python静态方法。分享给大家供大家参考。 具体实现方法如下: 复制代码 代码如下:staticmethod Found at: __builtin__ staticme...

Python压缩和解压缩zip文件

zip文件是我们经常使用的打包格式之一,python解压和压缩zip效率非凡。 python解压zip文档: 复制代码 代码如下: #/usr/bin/python #coding=ut...